Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTable : No selected row

Tags:

java

swing

I want to disable a button whenever there aren't any rows selected in a jTable. Is there any possible way to do this?

like image 858
cassrynne Avatar asked Dec 29 '22 04:12

cassrynne


2 Answers

Use a 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());
});
like image 91
justkt Avatar answered Jan 08 '23 02:01

justkt


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);
        }
    }
});
like image 26
Uhlen Avatar answered Jan 08 '23 01:01

Uhlen