且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jtable cellrenderer在运行时更改单元格的背景颜色

更新时间:2023-12-03 11:53:22

不要更新CutomRenderer类中的表数据。渲染器类应检查条件并为单元格着色。我使用了 CustomRenderer 类,并根据单元格中的数据渲染单元格。如果单元格的数据为Y,则将其变为黄色。如果数据为N,则将其颜色设置为灰色。

Do not update table data in your CutomRenderer class. You Renderer class should check the condition and color the cells. I have used your CustomRenderer class and rendered the cells basing on the data present in the cells. If the data of the cell is 'Y' color it to Yellow. If the data is 'N' then color it to Grey.

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;


public class ColoringCells {

    private static Object[] columnName = {"Yes", "No"};
    private static Object[][] data = {
            {"Y", "N"},
            {"N", "Y"},
            {"Y", "N"}
    };


    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {

                JFrame frame = new JFrame();
                JTable table = new JTable(data, columnName);
                table.getColumnModel().getColumn(0).setCellRenderer(new CustomRenderer());
                table.getColumnModel().getColumn(1).setCellRenderer(new CustomRenderer());

                frame.add(new JScrollPane(table));
                frame.setTitle("Rendering in JTable");
                frame.pack();
                frame.setVisible(true);
            }
        };

        EventQueue.invokeLater(r);
    }
}


class CustomRenderer extends DefaultTableCellRenderer 
{
private static final long serialVersionUID = 6703872492730589499L;

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

        if(table.getValueAt(row, column).equals("Y")){
            cellComponent.setBackground(Color.YELLOW);
        } else if(table.getValueAt(row, column).equals("N")){
            cellComponent.setBackground(Color.GRAY);
        }
        return cellComponent;
    }
}