I want to disable a button whenever there aren't any rows selected in a jTable. Is t开发者_StackOverflow社区here any possible way to do this?
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());
});
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);
}
}
});
Add an selection Listener to your table. If an selection occurs, enable the button. Let the Button be disabled by default.
http://download.oracle.com/javase/6/docs/api/javax/swing/JTable.html
精彩评论