'Multiple buttons in one table column in Java Swing won't perform action
What I need is to dynamically add buttons to one JTable column. Each row can have 0-N buttons in this column. I figured how to add these buttons but after clicking on them nothing happens, despite each button has action listener specified.
In addition, right after I create these buttons I need to set ActionListeners to it, so that when this button is clicked, some action will be done (action outside of TasksCell class).
Here is how I set renderer and editor and how I create buttons :
table.setDefaultRenderer(Tasks.class, new TasksCell());
table.setDefaultEditor(Tasks.class, new TasksCell());
//
//
//
ActionListener listener = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// DOING STH
}
};
JButton button = new JButton("task");
button.addActionListener(listener);
// tableModel is custom TableModel
tableModel.addNewTask(button);
This is how I add task(button) to my class for storing buttons in my custom table model:
// I need to calculate where to add button, row is index of the row in table
((Tasks)this.getValueAt(row, 3)).addTask(task);
Then this is my class for storing buttons :
public class Tasks {
private List<JButton> taskButtons = new ArrayList<>();
public void addTask(JButton task) {
taskButtons.add(task);
}
public List<JButton> getTaskButtons() {
return taskButtons;
}
public void setTaskButtons(List<JButton> tasks) {
this.taskButtons = tasks;
}
}
And finally class with table cell editor and renderer :
public class TasksCell extends AbstractCellEditor implements TableCellEditor, TableCellRenderer {
@Override
public Object getCellEditorValue() {
return null;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
Tasks tasks = (Tasks)value;
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
tasks.getTaskButtons().forEach(task -> {
panel.add(task);
});
panel.setBackground(table.getSelectionBackground());
return panel;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Tasks tasks = (Tasks)value;
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
tasks.getTaskButtons().forEach(button -> {
panel.add(button);
});
panel.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
return panel;
}
}
As I mentioned before, buttons are added to panel in table correctly
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
