如何正确使用自定义渲染器在 JTable 中绘制特定单元格?

编程入门 行业动态 更新时间:2024-10-26 20:30:46
本文介绍了如何正确使用自定义渲染器在 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 中绘制特定单元格?

本文发布于:2023-11-23 02:07:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619707.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   单元格   如何正确   渲染器   JTable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!