“突出显示" JTable中的特定行 [英] "Highlighting" specific rows in a JTable
问题描述
只要单元格的内容与用户的输入相匹配,我都希望突出显示JTable中的特定行.到目前为止,下面的代码是我能运行的代码:
I would like to highlight specific rows in a JTable whenever the contents of the a cell match with an input from the user. The following code is what I have that works thus far:
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
.
Notes: hashMapcontainer
is a hashmap
that is globally scoped within the source file.
现在这在某种程度上可行,但是,我将此JTable
添加到JFrame
内的JTabbedPane
中. JTable是在程序运行时动态创建的.但是,prepareRenderer
方法使所有创建的JTables中的所有特定单元格突出显示.
Now this works to some extent however, I am adding this JTable
to a JTabbedPane
that is within a JFrame
. JTables are dynamically created throughout the runtime of the program. However, the prepareRenderer
method causes all the specific cells in all the created JTables to be highlighted.
我如何在所有JTable中保留单元格以保留其特定的突出显示单元,而不是让所有JTable在每个JTable中具有完全相同的突出显示的单元格?
How can I keep cells in all the JTables to keep their own specific highlighted cells rather than having all the JTables with the same exact highlighted cells in each?
提前谢谢!
推荐答案
渲染器是橡皮图章".这基本上意味着他们将先前的设置保留到下一个单元格.
The renderers are "rubber stamps". That basically means that they carry there previous settings over to the next cell.
您需要做的是提供默认"行为
What you need to do is provide a "default" behavior
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
可能是一个公平的解决方案,但您确实应该探索提供基线渲染器的可能性.这是一项很艰巨的工作,但是具有可移植性(如果您更改表实现)以及允许其他功能的优点.
人们有机会定义给定单元格的突出显示规则,恕我直言,您基本上已经删除并覆盖了这些规则.
While I personally think that prepareRenderer
in this case is probably a fair solution, you really should explore the possibly of providing a base line renderer. This is a lot of work to get right but has the advantage of been portable (if you change table implementations) as well as allowing other
people the chance to define the highlight rules of a given cell, which you've basically just gone and overridden, IMHO.
我还建议您看一下 JXTable ,因为它内置于
I'd also suggest taking a look at JXTable as it has in built highlighting
这篇关于“突出显示" JTable中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!