gpt4 book ai didi

java - 如何在jtable中动态设置行的颜色?

转载 作者:太空宇宙 更新时间:2023-11-04 06:39:16 25 4
gpt4 key购买 nike

看了很多文章但不明白怎么做!

我想更改 JTable 中某些行的颜色。该表有 3 列:a、b 和 c。

规则

  1. 如果a的值<=b则整行的颜色必须是红色
  2. 如果a的值>=c则整行的颜色必须是黄色
  3. 默认情况下,行的颜色必须为蓝色。

最佳答案

尝试以下代码

public class IconifiedRenderer extends JLabel implements TableCellRenderer {
public IconifiedRenderer() {
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel label = this;
int cellValueA=-1;
int cellValueB=-1;
int cellValueC=-1;
try {
setOpaque(true);
label.setText(String.valueOf(value));
try {
cellValueA = Integer.parseInt(String.valueOf( table.getValueAt(row, 0))); //0th for A
} catch (ArrayIndexOutOfBoundsException aa) {
//ignore
cellValueA=-1;
}
try {
cellValueB = Integer.parseInt(String.valueOf( table.getValueAt(row, 1))); //1th for A
} catch (ArrayIndexOutOfBoundsException aa) {
//ignore
cellValueB=-1;
}
try {
cellValueC = Integer.parseInt(String.valueOf( table.getValueAt(row, 2))); //2th for A
} catch (ArrayIndexOutOfBoundsException aa) {
//ignore
cellValueC=-1;
}
label.setBackground(Color.BLUE);

if(cellValueA<=cellValueB){
label.setBackground(Color.RED);
}
if(cellValueA>=cellValueC){
label.setBackground(Color.YELLOW);
}
} catch (Exception ex) {
// no need to handle
}
return label;
}

添加此渲染类并在表格列上设置渲染

    jTable1.getColumnModel().getColumn(0).setCellRenderer(new IconifiedRenderer());
jTable1.getColumnModel().getColumn(1).setCellRenderer(new IconifiedRenderer());
jTable1.getColumnModel().getColumn(2).setCellRenderer(new IconifiedRenderer());

它会像这样显示你的表格...

enter image description here

关于java - 如何在jtable中动态设置行的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24901424/

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