How to clear contents of selected cells in JTable?

Chauncey Lee

I use mouse to drag a selection area in some JTable cells, the selection area is the yellow, so can anyone told me exactly how to clear the contents of selected cells by pressing "Delete" key in keyboard or a JButton?

The captured pic of selected cells:

https://i.stack.imgur.com/2FvkU.png

camickr

Create an Acton to find the selected cells and clear the text. The easiest way is to loop through each cell in the table.

The basics of the Action would be something like:

Action clearAction = new Action()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        for (each row in the table)
            for (each column in the row)
                if (table.isCellSelected(...))
                   table.setValueAt("", ...);
    }
}

Then you create a button to invoke the Action:

JButton clearButton = new JButton( "Clear" );
clearButton.addActionListener( clearAction );

If you also want to use the Delete key then you can use Key Bindings to share the same Action.

The basic logic to add a new Key Binding to the JTable would be:

String keyStrokeAndKey = "DELETE";
KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(keyStroke, keyStrokeAndKey);
table.getActionMap().put(keyStrokeAndKey, action);

Check out Key Bindings for more information.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related