如何正确使用自定义渲染器在 JTable 中绘制特定单元格? [英] How do I correctly use custom renderers to paint specific cells in a 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) 被着色?
推荐答案
在 if
中添加 else 子句:
Add an else clause to your if
:
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屋!