我正在尝试为我的一些 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/