我想为 jtable 的某些特定单元格着色。这是我的渲染类。我将 sysout 放在 if
block 上。打印了所有字符串,但单元格的颜色除了其中一个没有改变。
public class MyRenderer extends DefaultTableCellRenderer {
static double rpmMin, rpmMax, speedMin, speedMax, temperatureMin, temperatureMax, voltageMin, voltageMax;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (!table.isRowSelected(row)) {
if (column == 2 && Double.parseDouble(value.toString()) > rpmMin
&& Double.parseDouble(value.toString()) < rpmMax) {
c.setBackground(Color.PINK);
}
if(column == 3 && Double.parseDouble(value.toString()) > speedMin
&& Double.parseDouble(value.toString()) < speedMax){
c.setBackground(Color.PINK);
}
if (column == 4 && Double.parseDouble(value.toString()) > temperatureMin
&& Double.parseDouble(value.toString()) < temperatureMax) {
c.setBackground(Color.PINK);
}
if(column == 5 && Double.parseDouble(value.toString()) > voltageMin
&& Double.parseDouble(value.toString()) < voltageMax){
c.setBackground(Color.PINK);
}
else {
c.setBackground(Color.GREEN);
}
}
return c;
}
}
Here is the output of my program. Only the first unsuitable value is colored pink.
我准备了一个 excel 来显示正确的输出。 Here is the picture that I expected to see as output of this program
我不知道为什么它不起作用。有人可以向我解释一下吗?非常感谢:)
最佳答案
逻辑陷阱。您的个人 ifs 工作正常,只是您的最后一个 if 是一个 if/else 语句,它将把所有东西都变成绿色,除非它是适当的粉红色。
所以基本上,前 4 个 if 语句被忽略,因为只有最后一个决定它是绿色还是粉红色。
另外,出于理智的目的,解析一次,重复使用两次或更多次。
Double val = Double.parseDouble(value.toString());
if (column == 2 && val > rpmMin
&& val < rpmMax) {
c.setBackground(Color.PINK);
}
else if(column == 3 && val > speedMin
&& val < speedMax){
c.setBackground(Color.PINK);
}
else if (column == 4 && val > temperatureMin
&& val < temperatureMax) {
c.setBackground(Color.PINK);
}
else if(column == 5 && val > voltageMin
&& val < voltageMax){
c.setBackground(Color.PINK);
}
else {
c.setBackground(Color.GREEN);
}
关于java - 如何根据单元格的值为 jtable 的单元格着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38574899/