-1

Why does this code throws ClassCastException.when I am trying to set selected row value of JTable(ie.showItem) to a TextField (ie.itemCode).Exception is Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

 showItem = new JTable();
        showItem.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int rowCount=showItem.getRowCount();
                if(rowCount>=1){
                    //Why it is throwing ClassCastException
                     itemCode.setText((String)showItem.getValueAt(showItem.getSelectedRow(), 0));

                }
            }
        });

3 Answers3

1

First of all don't try to write all your code in a single statement. Its is easier to debug using multiple statements:

itemCode.setText((String)showItem.getValueAt(showItem.getSelectedRow(), 0));

Can easily be written as:

Object value = showItem.getValueAt(rowCount, 0);
itemCode.setText( value.toString() );

Note there is no need to invoke the getSelectedRow() method twice since you have a variable that contains that value.

Then you can always add some debug code like:

Object value = showItem.getValueAt(rowCount, 0);
System.out.println( value.getClass() );

to see what type of Object your table has in that cell.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

Maybe you should check this.

How do I convert from int to String?

for

itemCode.setText((String)showItem.getValueAt(showItem.getSelectedRow(), 0));
Community
  • 1
  • 1
0

You can't cast an Integer to String, because Integer is not a String, that is, Integer is not a subclass of String. However, you can pass the Integer to a String, since all Object have the toString() method.

Integer a = new Integer( 10 );
String myString = "" + a;
//Is the same  as String myString = "" + a.toString(), so you could do just
//String myString = a.toString();

I hope I have helped.

Have a nice day. :)

Saclyr Barlonium
  • 453
  • 4
  • 12