java - 将对象转换为 JTable?

标签 java swing

我正在尝试为我的一些 JTable 实现 ListSelectionListener。简单地(目前)ListSelectionListener 应该简单地返回所选单元格的文本。

我的程序设计有多个 JTable,我希望有一个 ListSelectionListener 可以为所有这些 JTable 工作。在 ListSelectionListener 的 valueChanged 事件中,我认为可以执行以下操作:

private class SelectionHandler implements ListSelectionListener {
    public void valueChanged(ListSelectionEvent e)
    {
        JTable table = (JTable)e.getSource();                                                         

        String data = (String) table.getValueAt(table.getSelectedRow(), 0);

        // Print data
    }
}

在幕后,我使用了以下代码来让 SelectionHandler 处理相关表:

fbTable.setCellSelectionEnabled(true);
ListSelectionModel cellSM = fbTable.getSelectionModel();
cellSM.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionModel.addListSelectionListener(selectionHandler);

当我运行该程序时,出现 ClassCastException 错误:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.DefaultListSelectionModel cannot be cast to javax.swing.JTable
        at cardboardfantasy.CardboardFantasyView$SelectionHandler.valueChanged(CardboardFantasyView.java:360)

// This is the line in question: JTable table = (JTable)e.getSource();

有没有办法做这样的事情?我想到的一种解决方案是将事件源 (e.getSource()) 与我的所有 JTable 进行比较,看看它们是否等效(大 if block ),然后在该 block 内调用 .getValueAt 但这会使代码将来如果要添加或删除表格会很困难。

最佳答案

在 IDE 中调试代码,设置断点并查看 e.getTarget() 的类型:

Object source = e.getSource();
JTable table = (JTable)source; // breakpoint on this line and inspect the variable 'source'
String data = (String) table.getValueAt(table.getSelectedRow(), 0);

或者,如果由于某种原因无法进行调试,请执行以下操作:

Object source = e.getSource();
System.out.println(source.getClass());

但是:使用 System.out.println 进行调试是邪恶的。您的调试器是您的 friend 。

关于java - 将对象转换为 JTable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2860449/

相关文章:

java - 插入顶部链接后无法加载实体

java - 为什么 Java 中的 multi-catch 特性要求异常是最终的?

java - Dspace XMLUI 配置

java - 如何从某一点向前设置文本颜色

java - 从 JDateChooser 获取日期并将其显示在 JTextField 中

JDialog 关闭后 Java JComponent 不重新绘制

java - java中Graphics2D中的鼠标点击事件

java - 有没有办法将扩展 WebMvcConfigurerAdapter 和 WebSecurityConfigurerAdapter 的 @Configurations 合并到一个 @Configuration 中?

java - 为什么 setBackground 到 JButton 不起作用?

java - Eclipse 中的 Ant 构建失败 : Unable to understand the error from console