簡體   English   中英

動態更改 JTable 單元的顏色

[英]Changing the color of a JTable cell DYNAMICALLY

我想知道如何在沒有用戶響應的情況下更改表格中單元格的背景顏色。 例如,如果我的一個變量由於一些不相關的方法調用而發生變化,我希望將其反映在我的表中。 例如,一個方法更改了我用來初始化表的數組的值,但是用戶沒有參與其中,例如經過時間的值更改。 那么我如何將它反映在我的桌子上,或者有什么方法可以手動調用 TableCellRenderer

編輯: 在此處使用代碼片段更新問題

建議使用自定義單元格渲染器:

import java.awt.Color;
import java.awt.Component;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;

public class CellRenderDemo {

    private static final int MAX =120;
    private static Object[] columnName = {"Item", "Value"};
    private static Object[][] data = {{"Value A", 12}, {"Value B", 34},  {"Value C", 66}};
    private final JTable table;

    CellRenderDemo() {
        table = new JTable(data, columnName);
        table.getColumnModel().getColumn(1).setCellRenderer(new CustomRenderer());//use custom cell rendered for col 1
    }

    void randomizeData(){
        Random rnd = new Random();
        TableModel model = table.getModel();
        new Timer(1000, e->{
            model.setValueAt(rnd.nextInt(MAX+1), rnd.nextInt(model.getRowCount()), 1);
        }).start();
    }

    JTable getTable() {
        return table;
    }

    static class CustomRenderer extends DefaultTableCellRenderer {

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

            int cellValue = (int)value;
            if(cellValue <= MAX / 3){ //change color based on value 
                cellComponent.setBackground(Color.PINK);
            } else if ( cellValue > 2*MAX / 3){
                cellComponent.setBackground(Color.CYAN);
            } else {
                cellComponent.setBackground(Color.YELLOW);
            }
            return cellComponent;
        }
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            JFrame frame = new JFrame();
            CellRenderDemo cd = new CellRenderDemo();
            frame.add(new JScrollPane(cd.getTable()));
            frame.pack();
            cd.randomizeData();
            frame.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}

在此處輸入圖像描述

暫無
暫無

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

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