【问题标题】:Set Background Color of a clicked table cell设置单击的表格单元格的背景颜色
【发布时间】:2015-06-02 16:30:36
【问题描述】:

我是 Java 新手,我想更改 JTable 的特定单元格(我单击的那个单元格)的背景颜色。

我知道我必须使用MouseListener,我已经使用了mousePressed。但在这一点上,我很迷茫。

编辑:忘记添加表格已禁用,因此您无法选择单元格。

谁能帮帮我?谢谢!

【问题讨论】:

    标签: java jtable cell background-color


    【解决方案1】:

    您必须创建一个自定义TableCellRenderer 并将其传递给表

    喜欢这个

    public class ColorRenderer extends DefaultTableCellRenderer {
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)  {
           // get the DefaultCellRenderer to give you the basic component
           Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
           // apply your rules
           if(table.isRowSelected(row) && table.isColumnSelected(col))
              c.setBackground(Color.GREEN);
           else{    
               c.setBackground(table.getBackground());
           }
    
           return c;
        }
    }
    

    在这个类中,我们检查给定的单元格是否是选定的单元格(当我们单击它时几乎会发生这种情况)并以不同的方式绘制它(在我的情况下,我将它绘制为绿色),否则我们使用默认颜色或任何你喜欢的颜色。

    别忘了设置刚刚创建的自定义渲染器

    table.setDefaultRenderer(Object.class, new ColorRenderer());
    


    编辑 1

    你必须得到被点击单元格的行和列。

    创建 2 个将保持位置的 int 变量

    private int clickedRow=-1,clickedCol=-1;
    

    添加一个更新位置变量的鼠标监听器

    table.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent event) {
                    clickedRow= table.rowAtPoint(event.getPoint());
                    clickedCol= table.columnAtPoint(event.getPoint());
                }
    });
    

    之后您更改渲染器,使其仅用特殊颜色绘制单击的单元格

    if( clickedRow == row && clickedCol == col){
        c.setBackground(Color.GREEN);
    }
    

    【讨论】:

    • 感谢您的回答。我忘了补充说整个表格都被禁用了,所以不可能“选择”一个单元格,只能点击它。这甚至可能吗?
    • 我已经更新了我的答案。第二种方法我还没有真正尝试过,告诉我它是否有效。
    猜你喜欢
    • 2012-06-06
    • 2019-10-21
    • 2010-11-21
    • 2017-02-08
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多