gpt4 book ai didi

java - 根据列值更改 JTable 整行的背景颜色

转载 作者:行者123 更新时间:2023-11-30 06:59:25 25 4
gpt4 key购买 nike

所以我想做的是根据最后一列内的值更改每一行的颜色。

我已经找到了这个解决方案:Change Background Color of JTable效果很好。

但另外我想在第四列达到与第二列相同的值时将行的颜色切换为绿色。

我使用了 Cristian Marian 的方法并编写了自己的类

    @Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component comp = super.prepareRenderer(renderer, row, column);


int second = (int) this.getModel().getValueAt(row, 1);
int forth = (int) this.getModel().getValueAt(row, 3);
int kat = Kategorie.getNumber((String) this.getModel().getValueAt(row, 2));
if (kat > 0) {
if (second == forth) {
comp.setBackground(Color.GREEN);
} else {
comp.setBackground(Color.RED);
}
}

return comp;
}

仍然只有每列中的最后一个单元格变为绿色,而不是整个单元格。但是当我在该行打卡时,整行都会切换颜色

最后一列中的值被另一帧更改。

开头的表格: http://i.stack.imgur.com/qIIVf.jpg

当最后一列中的值与第二列中的值相同时,它看起来像这样:

达到给定值后: http://i.stack.imgur.com/pSzU7.jpg

最佳答案

您的方法的问题是您使用 getTableCellRendererComponent 因此只有该单元格的颜色会改变。

我不得不做一些类似的事情。根据列的值,我必须为该行着色。

我使用了一个扩展 JTable 和重写 prepareRenderer 的类

@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component comp = super.prepareRenderer(renderer, row, column);
if (populated) { //this if was just to make sure that I have data in my table
/*
*This piece makes the code ignore the rows that are selected as this approach messes up that blue color that selected rows get
*/
int[] rows = this.getSelectedRows();
boolean rowisSelected = false;

for (int rowIndex : rows) {
if (row == rowIndex) {
rowisSelected = true;
break;
}
}
/*
*And this is the part that does the coloring
*/
if (!rowisSelected) {
Integer status = Integer.parseInt((String)
int modelRow = convertRowIndexToModel(row);
this.getModel().getValueAt(modelRow, Constants.HIDDEN_COLUMN));
switch (status) {
case 1:
comp.setForeground(Color.BLACK);
comp.setBackground(Color.WHITE);
break;
case 2:
comp.setForeground(Color.LIGHT_GRAY);
comp.setBackground(Color.WHITE);
break;
case 3:
comp.setForeground(Color.BLACK);
comp.setBackground(Constants.DOWNLOADED_COLOR);
break;
case 4:
comp.setForeground(Color.LIGHT_GRAY);
comp.setBackground(Constants.DOWNLOADED_COLOR);
break;
}
}
}
return comp;
}

你的应该是这样的(没有选择行的东西):

@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component comp = super.prepareRenderer(renderer, row, column);
int modelRow = convertRowIndexToModel(row);
String second = this.getModel().getValueAt(modelRow, 1));
String forth= this.getModel().getValueAt(modelRow, 3));
if(second.equals(forth)){
comp.setBackground(Color.GREEN);
}
return comp;
}

关于java - 根据列值更改 JTable 整行的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31585718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com