我正在使用Java Swing制作带有按钮的表,我可以将其用作基于行的操作。
我正在使用自定义单元格渲染器来尝试在表格单元格中渲染多个按钮。我设法拼凑出一些可以在视觉上实现我想要的功能的按钮,但是这些按钮实际上并未起作用。它们只是不会触发,并且不会对点击或鼠标悬停做出视觉反应。寻找一种使按钮做出反应并实际触发其动作的方法。
单元格渲染器类:
public class ButtonsCell extends AbstractCellEditor implements TableCellEditor, TableCellRenderer {
JPanel panel;
public ButtonsCell() {
this.updateData(Collections.emptyList());
}
private void updateData(List<JButton> buttons) {
this.panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
for(JButton button : buttons) {
button.setMargin(new Insets(-2, 0, -2, 0));
this.panel.add(button);
}
}
private void updateData(List<JButton> buttons, boolean isSelected, JTable table) {
this.updateData(buttons);
if (isSelected) {
this.panel.setBackground(table.getSelectionBackground());
}else{
this.panel.setBackground(table.getBackground());
}
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
this.updateData((List<JButton>)value, isSelected, table);
return panel;
}
public Object getCellEditorValue() {
return null;
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
this.updateData((List<JButton>)value, isSelected, table);
return panel;
}
}
在视觉上,这会产生: