Remove selection from a row of a JTable - Java

0

When I click on a row, all that row is selected but I would like to know how to do so that when I click on another place outside the Jtable the selection is removed, I share the code I use to select the row and an image.

tbDocTransferir.setColumnSelectionAllowed(true);
tbDocTransferir.setCellSelectionEnabled(true);

    
asked by Bruno 19.01.2017 в 15:21
source

1 answer

1

What you could do would be to add a FocusListener to your tbDocTransferir.

tbDocTransferir.addFocusListener(new FocusListener() {
                @Override
                public void focusGained(FocusEvent fe) {
                    tbDocTransferir.setColumnSelectionAllowed(true);
                    tbDocTransferir.setCellSelectionEnabled(true);
                }

                @Override
                public void focusLost(FocusEvent fe) {
                    tbDocTransferir.setColumnSelectionAllowed(false);
                    tbDocTransferir.setCellSelectionEnabled(false);
                }
            }

            });

This will only cause that when the focus gains the table can be selected, but when it loses it, this will only cause that when a different element of the table is selected, it loses focus, if it squeezes to some other part of the frame that does not be a component will not lose focus, for this you can add a mouseclicked to your frame so that when you click on any part of the frame that is not a component also perform the same action

this.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent me) {
                    tbDocTransferir.setColumnSelectionAllowed(false);
                    tbDocTransferir.setCellSelectionEnabled(false);
                } 
 });

everything would be put in the frame's constructor

You can also add the mouseClicked in the jtable.

tbDocTransferir.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent me) {
                    tbDocTransferir.setColumnSelectionAllowed(true);
                    tbDocTransferir.setCellSelectionEnabled(true);
                } 
 });
    
answered by 19.01.2017 в 15:49