JTable: no row selected

I want to disable the button if there are no lines in jTable. Is there any way to do this?

+3
source share
3 answers

Use SelectionListener on your JTable.

JTable table = new JTable();
JButton button = new JButton();
button.setEnabled(false);

ListSelectionModel listSelectionModel = table.getSelectionModel();
listSelectionModel.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) { 
            ListSelectionModel lsm = (ListSelectionModel)e.getSource();
            button.setEnabled(!lsm.isSelectionEmpty());
});
+6
source

Something like this should work:

table.getSelectionModel().addListSelectionListener(new ListSelectionListener()
{
    @Override
    public void valueChanged(ListSelectionEvent e)
    {
        if (!e.getValueIsAdjusting())
        {
            boolean rowsAreSelected = table.getSelectedRowCount() > 0;
            button.setEnabled(rowsAreSelected);
        }
    }
});
+3
source

Add a listener to the table. If a selection occurs, turn on the button. Let the button be disabled by default.

http://download.oracle.com/javase/6/docs/api/javax/swing/JTable.html

0
source

Source: https://habr.com/ru/post/1779427/


All Articles