TableCellRenderer选择单元格问题
我想实现 JTable 组件的 tablecellrenderer,它应该根据单元格数据显示不同的颜色。我明白了,但我无法更改所选单元格的颜色。我尝试这样做:
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex)
{
if (isSelected) {
this.setBackground((Color)UIManager.get("Table.selectionBackground"));
this.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
} else {
this.setForeground((Color)UIManager.get("Table.foreground"));
this.setBackground((Color)UIManager.get("Table.background"));
this.setBorder(BorderFactory.createEmptyBorder());
}
...
}
但它不起作用:S ..我看不到问题,因为当我单击单元格时,JTable 没有显示任何不同的内容。
I want to implement a tablecellrenderer of a JTable component, which should show a different color depending on the cell data. I got this, but I can't change the color of the selected cell. I tried to do this:
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex)
{
if (isSelected) {
this.setBackground((Color)UIManager.get("Table.selectionBackground"));
this.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
} else {
this.setForeground((Color)UIManager.get("Table.foreground"));
this.setBackground((Color)UIManager.get("Table.background"));
this.setBorder(BorderFactory.createEmptyBorder());
}
...
}
but it does not work :S .. I can not see the problem because the JTable does not show anything different when I click on a cell.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
。您发布的代码不会执行此操作。基本上您的所有代码所做的都是复制渲染器的默认行为
您可能会发现 表行渲染方法更容易实现。
The code you posted does not do this. Basically all your code does is duplicate the default behaviour of the renderer
You may find the Table Row Rendering approach easier to implement.
假设您使用 JLabel 作为组件的基础,那么设置背景将不会产生任何效果,除非您还将 opaque 设置为 true。 JLabels 默认为不透明,因此不绘制背景。
Assuming you're using a JLabel as the base of the component, setting the background will have no effect unless you also set opaque to true. JLabels default to not opaque and so do not paint the background.