I have a JTable
with custom renderers. When an item in the JTable
is clicked, I perform a specific set of actions that affect my model. I have two choices to implement this:
ListSelectionListener
: I add a listener on my entire JTable
which fires when a row is clicked. Then I perform the actions.
- Advantages: Allows me to select any part of the row (not required in my case), probably the way Swing intended for events to be fire in a
JTable
- Disadvantages: I have to create a custom class to handle this and reproduce code.
Example:
class Selector implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent event) {
// ... write the action code here
}
}
JButton & Action
: I render a JButton
and add an Action
to that JButton
.
- Advantages: I can reuse that
Action
, and if I change thatAction
, all instances using it will be updated. - Disadvantages: I move logic into my rendering code.
Example:
class Renderer implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int col) {
JButton btn = new JButton(value.toString());
btn.setAction(new SpecificAction());
return btn;
}
}
If I use the second solution, will fire rain down from the heavens?
Are they both equally viable?
Is there some way to use
Action
s inside aListSelectionListener
?