如何正确使用自定义渲染器绘制JTable中的特定单元格? [英] How do I correctly use custom renderers to paint specific cells in a JTable?

查看:360
本文介绍了如何正确使用自定义渲染器绘制JTable中的特定单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的GUI中有一个JTable组件,它显示算法的 psuedocode 。我想通过更改特定单元格的背景然后更改下面的单元格等来突出显示当前执行的行。等等。

I have a JTable component in my GUI which displays psuedocode of an algorithm. I want to highlight the current line of execution by changing the background of a particular cell and then changing the cell beneath and so on.

现在我的代码更改了背景我的JTable中的所有单元格如下图所示:

Right now my code changes the backgrounds on all cells in my JTable as pictured below:

我用来存档当前状态的代码如下:

The code I am using to archive this current state is as below:

class CustomRenderer extends DefaultTableCellRenderer 
{
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
            JLabel d = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if((row == 0) && (column == 0))
                d.setBackground(new java.awt.Color(255, 72, 72));
            return d;
        }
    }

然后我调用 jTable2。 setDefaultRenderer(String.class,new CustomRenderer()); 在我的构造函数中。

I then call jTable2.setDefaultRenderer(String.class, new CustomRenderer()); in my constructor.

我认为:


  • 在每个String类型表格单元格上调用此方法。

  • 这只会改变位置处单元格的颜色( 0,0)

如何修复我的代码以便只有单元格(0,0)被着色?

推荐答案

中添加else子句,如果

if ((row == 0) && (column == 0)) {
    d.setBackground(new java.awt.Color(255, 72, 72));
}
else {
    d.setBackground(Color.WHITE);
}

请记住,相同的渲染器实例用于绘制所有单元格。

Remember that the same renderer instance is used to paint all the cells.

这篇关于如何正确使用自定义渲染器绘制JTable中的特定单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆