【发布时间】:2021-08-28 02:25:07
【问题描述】:
我有一个 9x9 单元格的 JTable。我想处理在 JTable 中选择单元格的事件。我想在单元格被选中时更改它的背景颜色。
这个代码我已经试过了
public class JSudokuTable extends JTable {
public JSudokuTable() {
super(9, 9);
setRowHeight(60);
setForeground(Color.WHITE);
setBackground(Color.WHITE);
setGridColor(Color.CYAN);
setRowSelectionAllowed(false);
setSelectionForeground(Color.WHITE);
setSelectionBackground(Color.YELLOW);
setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Color color,
boolean isSelected, boolean hasFocus, int row, int column) {
JLabel comp = (JLabel) super.getTableCellRendererComponent(table, color, isSelected, hasFocus, row, column);
if (isSelected)
comp.setBackground(Color.YELLOW);
else
comp.setBackground(Color.WHITE);
return comp;
}
});
}
}
此代码不会导致单元格 (JLabels) 在选中时更改背景颜色。如何处理 JTable 中单元格被选中的事件?
【问题讨论】:
-
你调试你的渲染器了吗?代码执行了吗? isSelectred 变量是否包含您期望的值?如果您需要更多帮助,请发布适当的minimal reproducible example。我们无法复制/粘贴/执行/测试提供的代码。