选择新单元格后,如何保持彩色 jTable 单元格的颜色?

How do i keep a colored jTable cell colored after selecting a new one?

我很难理解 cellrenderer 并找到特定问题的解决方案。 我想在选中时专门为单元格着色,然后单击一个按钮,然后让程序提醒哪些单元格已经着色,哪些没有。因此,如果我给其中一个着色,它应该在其余时间保持着色,直到开始新游戏。 到目前为止,我确实可以为单元格着色,但我无法弄清楚如何使 jTable 保持彩色单元格的颜色。

我在带有 GUI 的 Netbeans 中工作。这是我的第一次,我是初学者,所以请对我和我的代码保持温和。我确实看过渲染教程等等,但是找不到可行的方法,或者我的小程序无法实现。

这是在 initcomponents() 之后;

jTableScoreFormulier.setDefaultRenderer(Object.class,new MyRenderer());

然后你得到这个部分来制作 table:

    jTableScoreFormulier.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {"Rood", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"},
            {"Geel", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"},
            {"Groen", "12", "11", "10", "9", "8", "7", "6", "5", "4", "3", "2"},
            {"Blauw", "12", "11", "10", "9", "8", "7", "6", "5", "4", "3", "2"}
        },
        new String [] {
            "Kleur", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "Sluit"
        }
    ));

这是我的渲染器:

class MyRenderer implements TableCellRenderer {

public final DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer();

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    Component renderer = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    Color foreground, background;
    if (isSelected) {
        foreground = Color.WHITE;
        background = Color.BLACK;
    }  else {
        foreground = Color.BLACK;
        background = Color.WHITE;
    }
    renderer.setForeground(foreground);
    renderer.setBackground(background);
    return renderer;
}
}

}

jTableScoreFormulier.setRowSelectionAllowed(true);
jTableScoreFormulier.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

这会启用多选

I can't figure out how to make the jTable keep the colored ones colored.

一种方法是将信息保存在 TableModel 中。因此,您可能只是在模型中存储 Boolean.TRUE 或 Boolean.FALSE 以指示选择了哪些单元格。所有单元格的默认值为 Boolean.FALSE 然后当您单击一个单元格时,您使用 setValueAt(Boolean.TRUE, row, column) 方法更新 TableModel 以更改选择。

然后你的渲染器代码变成:

//if (isSelected) {

Boolean colored = (Boolean)value;

if (colored) {
   ...