【问题标题】:How do you handle the event of a cell being selected in a JTable? [closed]您如何处理在 JTable 中选择单元格的事件? [关闭]
【发布时间】: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。我们无法复制/粘贴/执行/测试提供的代码。

标签: java swing jtable


【解决方案1】:
    public Component getTableCellRendererComponent(JTable table, Color color, 
            boolean isSelected, boolean hasFocus, int row, int column) {

在覆盖方法时,请务必使用@Override 来确保正确覆盖该方法:

@Override
public Component getTableCellRendererComponent(JTable table, Color color, 
        boolean isSelected, boolean hasFocus, int row, int column) {

当您错误地覆盖该方法时,您将收到一条编译消息。检查 API 以获取正确的参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    相关资源
    最近更新 更多