动态更改JTable单元的颜色

问题描述 投票:0回答:1

我想知道如何在没有用户任何响应的情况下更改表格中单元格的背景颜色。例如,如果由于某些不相关的方法调用而导致我的变量之一发生变化,那么我希望将其反映在表中。例如,一个方法改变了我用来初始化表的数组的值,但是用户却没有手,比如说值的经过时间改变。因此,如何将其反映在我的桌子上,或者有什么方法可以手动调用TableCellRenderer

java swing jtable
1个回答
0
投票

建议使用自定义单元格渲染器:

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);
    }
}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.