【问题标题】:Java: Clear selection from JTable by clicking on other space of the formJava:通过单击表单的其他空间从 JTable 中清除选择
【发布时间】:2014-03-30 06:00:59
【问题描述】:

通过单击表单的其他空间从 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

【问题讨论】:

标签: java swing jtable focus focuslistener


【解决方案1】:

通过单击从 JTable 中清除选择的最佳方法是什么 表格的其他空间?

这听起来像是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();
        }
    }            
});

看看:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 2015-02-22
    • 2015-11-26
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    相关资源
    最近更新 更多