gpt4 book ai didi

java - 更改 JTable 的单元格颜色时的不同更改

转载 作者:行者123 更新时间:2023-11-29 04:45:09 25 4
gpt4 key购买 nike

在我的 Java 程序中,我在配置表格单元格的颜色时遇到了问题。正如您在下面看到的,我在单元格中有 4 个不同的列组件。当我更改所有这些单元格的颜色时,只有 column1 的颜色发生变化。

DefaultTableModel tableModel = new DefaultTableModel(columns,0){
@Override
public Class<?> getColumnClass(int column) {
switch(column) {
case 0: return String.class;
case 1: return ImageIcon.class;
case 2: return Integer.class;
case 3: return Integer.class;
default: return Object.class;
}
}
};

我已经改变了单元格的颜色:

table1.setDefaultRenderer(Object.class, new ColorChange);
// I guess Object.class causes the problem
public class ColorChange implements TableCellRenderer {

public final DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer();

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

// Apply zebra style on table rows
if (row % 2 == 0) {
c.setBackground(Color.WHITE);
} else {
c.setBackground(Color.decode("#F8F8F8"));
}

return c;
}

}

那么问题是如何更改所有列的颜色?

提前谢谢你。

最佳答案

As you see below, I have 4 different column components in the cells. And when I change the colors of all these cells, just column1's color changing.

table1.setDefaultRenderer(Object.class, new ColorChange);

渲染器仅用于指定的类。 Object.class 被指定为没有特定渲染器的类的捕获所有类。

在您的情况下,它将仅用于 String 对象。 IconInteger 类已经有了自定义渲染器。

您还可以添加:

table1.setDefaultRenderer(Icon.class, new ColorChange);
table1.setDefaultRenderer(Integer.class, new ColorChange);

但是,如果您这样做,您将失去那些渲染器的自定义格式。如果您想继续使用这种方法,您将需要一个“IconColorChange”和“IntegerColorChange”渲染器。

相反,我建议您查看 Table Row Rendering对于一个解决方案,它允许您在仍然使用渲染器或表格的自定义格式的同时进行行级着色。这不需要创建自定义渲染器。

关于java - 更改 JTable 的单元格颜色时的不同更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37500636/

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