每当单元格的内容与用户的输入匹配时,我想突出显示 JTable 中的特定行。以下代码是我迄今为止可以使用的代码:
JTable table = new JTable(model) {
public Component prepareRenderer(
TableCellRenderer renderer, int row,
int column) {
Component c = super.prepareRenderer(renderer,
row, column);
if (!isRowSelected(row) ) {
c.setBackground((hashMapcontainer
.containsKey(row)) ? Color.GREEN
: getBackground());
}
return c;
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
注释:hashMapcontainer
是一个在源文件内具有全局作用域的 hashmap
。
现在这在某种程度上有效,但是,我将此 JTable
添加到 JFrame
内的 JTabbedPane
中。 JTable 是在程序运行期间动态创建的。但是,prepareRenderer
方法会导致所有创建的 JTable 中的所有特定单元格都突出显示。
如何保留所有 JTable 中的单元格以保留其自己特定的突出显示单元格,而不是让所有 JTable 中的每个单元格都具有完全相同的突出显示单元格?
提前致谢!
最佳答案
渲染器是“橡皮图章”。这基本上意味着它们将以前的设置传递到下一个单元格。
您需要做的是提供“默认”行为
if (!isRowSelected(row) ) {
c.setBackground((hashMapcontainer
.containsKey(row)) ? Color.GREEN
: getBackground());
} else {
// Define the default background color
// Don't forget to take into the selection state
}
虽然我个人认为在这种情况下 prepareRenderer
可能是一个公平的解决方案,但您确实应该探索提供基线渲染器的可能性。这需要做很多工作,但具有可移植的优点(如果您更改表实现)以及允许其他
人们有机会定义给定单元格的突出显示规则,恕我直言,您基本上已经删除并覆盖了这些规则。
我还建议查看 JXTable因为它内置highlighting
关于java - "Highlighting"JTable 中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11872003/