简体   繁体   English

比较单元格中的2个值并更改JTable中的单元格颜色

[英]compare 2 value from cell and change cell color in JTable

So i want to compare 2 value from 2 cells on the same row ("Initial Target" and "Result Target") from my table, and if the value is not the same the cell on "Result Target" column will turn red , but my code turn all cell to red, here's the result : 所以我想比较表中同一行(“ Initial Target”和“ Result Target”)中2个单元格的2个值,如果值不相同,则“ Result Target”列上的单元格将变为红色,但是我的代码将所有单元格都变成红色,结果如下:

result 结果

here's what i expect : 这是我的期望:

Expected 预期

here's my code : 这是我的代码:

tblResult = new JTable(tableModel) {
        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
            Component comp = super.prepareRenderer(renderer, row, col);
            Object value1 = getModel().getValueAt(row, 2);
            Object value2 = getModel().getValueAt(row, 1);
            if (value1!=value2) {
                    comp.setBackground(Color.red);
            }
             else {
                comp.setBackground(Color.white);
            }
            return comp;
        }
    };

If you are doing if (value1 != value2) you are just checking whether value1 and value2 have the same reference and here they don't so, this comparison will always return true . 如果您正在执行if (value1 != value2) ,则只是在检查value1value2是否具有相同的引用,而在这里它们不是相同的,此比较将始终返回true

What you can do instead is cast these objects to String or Integer like this: 相反,您可以执行以下操作将这些对象转换为String或Integer:

String value1 = (String) getModel().getValueAt(row, 2);
String value2 = (String) getModel().getValueAt(row, 1);

And then perform the comparison as follows: 然后执行如下比较:

if (!value1.equalsIgnoreCase(value2)) {}

You execute the logic for each columnIndex, so each rendering component has its color manipulated and is painted eg red. 您为每个columnIndex执行逻辑,因此每个渲染组件都有其颜色可操纵并被绘制成红色。 You should have some condition around like if(col == 2) and so only execute your color magic when the method prepareRenderer() is called for the 3rd column. 您应该有一些类似if(col == 2) ,因此只有在第三列调用prepareRenderer()方法时才执行颜色魔术。

Of cause the already mentioned comparison fix if (!value1.equalsIgnoreCase(value2)) {} should be done. 原因是已经提到的比较修复if (!value1.equalsIgnoreCase(value2)) {}

By the way, you might use table.getColumnModel().getColumn(2).setCellRenderer(TableCellRenderer) to set a specific rendering logic just for this column. 顺便说一句,您可以使用table.getColumnModel().getColumn(2).setCellRenderer(TableCellRenderer)来为此列设置特定的呈现逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM