Search code examples
javaswingjtablefocusfocuslistener

Java: Clear selection from JTable by clicking on other space of the form


What's the best way to clear selection from JTable by clicking on other space of the form? I tried this:

    table1.addFocusListener(new MyTableFocusListener());

    ...

    public class MyTableFocusListener implements FocusListener {
        @Override
        public void focusLost(FocusEvent e)
        {
            table1.getSelectionModel().clearSelection();
        }

        @Override
        public void focusGained(FocusEvent e)
        {
        }
    }

but got exception:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1

Solution

  • What's the best way to clear selection from JTable by clicking on other space of the form?

    It sounds like a job for MouseListener instead of FocusListener. Lets say your table is placed in some panel in your form. For instance:

    final JTable table = new JTable(model);
    JScrollPane scrollPane = new JScrollPane(table);
    
    JPanel formContent = new JPanel();
    formContent.add(scrollPane);
    

    You can add a MouseListener to this panel and use JTable.clearSelection() method as @MadProgramer has suggested:

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

    Take a look to: