簡體   English   中英

Java-更改JTable中某些單元格的顏色

[英]Java - Change colors of some cells in JTable

我有一個稱為SponsorIndexArr的整數數組,它包含要更改表中顏色的單元格的索引(我也想使該單元格不可選擇)。 該表是一列,因此我只需要單元格的行索引。

這是一些相關的代碼:

// Configure sponsor table
sponsorstableModel = new DefaultTableModel(sponsorsTableList, new String[]{"Sponsors"}
    @Override
    public boolean isCellEditable(int row, int column) {
       return false;
    }
};
sponsorsTable = new JTable(sponsorstableModel);
sponsorsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
sponsorsTable.addMouseListener(this);

sponsorsTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            for (int entry : sponsorIndexArr) {
                System.out.println(entry + " " + row);
                if (entry == row) {
                    System.out.println("HERE");
                    this.setBackground(Color.CYAN);
                    this.setEnabled(false);
                } else {
                    setBackground(null);
                    this.setEnabled(true);
                }
            }
            return this;
        }
    });

程序在正確的位置打印“ HERE”。 但是,正在發生的事情是,只有帶有SponsorIndexArr的最后一個索引的單元格正在更改顏色。 當我擺脫setBackground(null)每個單元格都會變成青色。

同樣,當我選擇任何其他單元格時,背景也會覆蓋文本。 當我擺脫this.setEnabled(true)我沒有這個問題,但是每個單元格都被禁用(文本變為灰色)。

發生的情況是,只有帶有SponsorIndexArr的最后一個索引的單元格正在更改顏色。

您對渲染器的概念是錯誤的。 渲染器有一個循環,指示您正在嘗試一次渲染所有單元。 這不是渲染器的工作方式

每個單元都使用相同的渲染器。 每次需要渲染單元時,都會調用渲染器。 因此,如果您有10行,則渲染器將被調用10次,並且渲染器的狀態將被更新10次以反映單元格的狀態。

我有一個稱為SponsorIndexArr的整數數組,其中包含我要更改顏色的單元格的索引

我建議您應該使用一Set整數。 然后,渲染器將進行簡單檢查,以查看行索引是否在集合中,然后確定應如何渲染單元格。

該代碼可能類似於:

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

    if (isSelected)
        setBackground( table.getSelectionBackground() );
    else if (yourSet.contains(row))
        setBackground( Color.CYAN );
    else
        setBackground( table.getBackground() );

    return this;
}

暫無
暫無

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

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