gpt4 book ai didi

java - JTable CellRenderer 仅在聚焦时更改前景色

转载 作者:行者123 更新时间:2023-12-02 08:49:35 24 4
gpt4 key购买 nike

我正在尝试实现一个根据整数值改变颜色的单元渲染器。然而,细胞的颜色仅在聚焦时才会改变。见下图。

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

switch (column) {
case 1:this.setFont(this.getFont().deriveFont(Font.BOLD)); break;
case 3:this.setFont(this.getFont().deriveFont(Font.BOLD)); break;
}
if (column == 4 && (Integer)value > 0) {
setForeground(Color.green);
} else {
setForeground(Color.red);
}
return this;
}

enter image description here

最佳答案

我猜您的表没有触发正确的更新事件,因此没有重绘单元格。

合并了无法重现问题的所有给定代码的 MRE:

import java.awt.*;
import javax.swing.*;

class Code extends javax.swing.table.DefaultTableCellRenderer {
public static void main(String[] args) throws Throwable {
java.awt.EventQueue.invokeLater(Code::go);
}
private static void go() {
JTable table = new JTable(
new Object[][] { { 0, 1, 2, 3, 4 }, { 1, 2, 3, 4, 5 } },
new Object[] { "0", "1", "2", "3", "3" }
);
table.setDefaultRenderer​(Object.class, new Code());
JFrame frame = new JFrame("Table");
frame.add(table);
frame.pack();
frame.setVisible(true);

new Timer(1000, event -> {
table.setValueAt(
-(Integer)table.getValueAt(0, 4),
0, 4
);
}).start();
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

switch (column) {
case 1:this.setFont(this.getFont().deriveFont(Font.BOLD)); break;
case 3:this.setFont(this.getFont().deriveFont(Font.BOLD)); break;
}
if (column == 4 && (Integer)value > 0) {
setForeground(Color.green);
} else {
setForeground(Color.red);
}
return this;
}
}

关于java - JTable CellRenderer 仅在聚焦时更改前景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60873086/

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