通过单击表单的其他空间来清除 JTable 中的选择的最佳方法是什么? 我试过这个:
table1.addFocusListener(new MyTableFocusListener());
...
public class MyTableFocusListener implements FocusListener {
@Override
public void focusLost(FocusEvent e)
{
table1.getSelectionModel().clearSelection();
}
@Override
public void focusGained(FocusEvent e)
{
}
}
但出现异常:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
最佳答案
What's the best way to clear selection from JTable by clicking on other space of the form?
这听起来像是 MouseListener 的工作而不是FocusListener 。假设您的表格放置在表单中的某个面板中。例如:
final JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
JPanel formContent = new JPanel();
formContent.add(scrollPane);
您可以向此面板添加一个 MouseListener
并按照 @MadProgramer 的建议使用 JTable.clearSelection()
方法:
formContent.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(!table.contains(e.getPoint())) { // contains(Point point) method is inherited from java.awt.Component
table.clearSelection();
}
}
});
看看:
关于Java:通过单击表单的其他空间来清除 JTable 中的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22057814/