簡體   English   中英

在改變JTable的單元顏色時進行不同的更改

[英]A different alteration while changing cell color of the JTable

在我的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;
    }

}

所以問題是我怎樣才能改變所有列的顏色?

先感謝您。

如下所示,我在單元格中有4個不同的列組件。 當我改變所有這些單元格的顏色時,只需改變column1的顏色。

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

渲染器僅用於指定的類。 Object.class是指定為沒有特定渲染器的類的catch all類。

在您的情況下,它將僅用於String對象。 IconInteger類已經有一個自定義渲染器。

您還可以添加:

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

但是,如果這樣做,您將失去這些渲染器的自定義格式。 如果要繼續使用此方法,則需要“IconColorChange”和“IntegerColorChange”渲染器。

相反,我建議您查看表格行渲染以獲得一個解決方案,該解決方案允許您在使用渲染器或表格的自定義格式時進行行級着色。 這不需要創建自定義渲染器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM