【问题标题】:Why does .setText() cause a ClassCastException?为什么 .setText() 会导致 ClassCastException?
【发布时间】:2017-03-10 22:40:36
【问题描述】:

为什么这段代码会抛出ClassCastException。当我试图将JTable(ie.showItem)的选定行值设置为TextField(ie.itemCode)时。异常是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));

                }
            }
        });

【问题讨论】:

  • 因为从getValueAt 返回的对象 - 一个整数,如异常消息所示 - 不能转换为字符串。这与setText 无关,是由用作参数的表达式引起的。还有其他问题吗?
  • @Mukund 显示 itemCode 类
  • 使用 .toString() 方法

标签: java swing jtable jtextfield


【解决方案1】:

您不能将Integer 转换为String,因为Integer 不是String,即Integer 不是String 的子类。但是,您可以将Integer 传递给String,因为所有Object 都有toString() 方法。

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();

我希望我有所帮助。

祝你有美好的一天。 :)

【讨论】:

    【解决方案2】:

    也许你应该检查一下。

    How do I convert from int to String?

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

    【讨论】:

      【解决方案3】:

      首先,不要试图在一条语句中编写所有代码。使用多个语句更容易调试:

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

      可以很容易地写成:

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

      请注意,不需要调用 getSelectedRow() 方法两次,因为您有一个包含该值的变量。

      然后您可以随时添加一些调试代码,例如:

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

      查看您的表格在该单元格中的对象类型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-06
        • 1970-01-01
        • 1970-01-01
        • 2013-02-25
        相关资源
        最近更新 更多