Java Swing:如何根据文本更改 JTable 列中每个单元格的颜色?

Java Swing: How do you change colors of very cell in a JTable column based on text?

我有一个基本的 JTable,其中填充了 "item number" 和该项目对应的 "color",我需要将包含该颜色名称的单元格的颜色更改为该实际颜色, 不管是否选中。

这是我的 JTable 的代码:

    String[] title = {"Item Number", "Color"};
    String[][] listOfValues = {{"1", "red"}, {"2", "blue"}, {"3", "green"}};

    JTable new_table = new JTable(listOfValues, title);
    JScrollPane table_pane = new JScrollPane(new_table);
    table_pane.setBounds(10, 10, 300, 230);
    frame.getContentPane().add(table_pane);

布局是临时的。这是 table 的样子:

因此,在此 table 中,包含 "red" 的单元格将为红色,包含 "blue" 的单元格将为蓝色,包含 "green" 的单元格将为绿色.所有其他单元格都保持白色。

我该如何实现?

您可以实现自己的 TableCellRenderer,在您的情况下,查找所有文本单元格,或查找第二列(您可以在 CellRenderer 实现中使用许多不同的创造性方法来定位您想要的目标单元格以特定方式呈现。)

此外,另一种替代方法是利用 JLabel 的 html 功能,然后在构建数据时执行此操作。这在简单的情况下也可以很好地工作,并且意味着您不必实现自己的渲染器,而不是像您这样的情况。您可以使用 JLabel 的 <html> 能力..

String colorString = "red";
String jLabelString = "<html><font color=" + colorString + ">" + colorString;

喜欢这种东西...

String[][] listOfValues = {{"1",jLabelString}, {"2","<html><font color=blue>blue"},etc,etc};

此代码允许更改行的颜色

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.examen.navegacion;

import java.awt.Color;
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

/**
 *
 * @author wilso
 */
public class Fiea {

    public static void main(String[] args) {
        JFrame frame = new JFrame("FrameDemo");
        String[] title = {"Item Number", "Color"};
        String[][] listOfValues = {{"1", "red"}, {"2", "blue"}, {"3", "green"}};

        JTable new_table = new JTable(listOfValues, title);
        JScrollPane table_pane = new JScrollPane(new_table);
        table_pane.setBounds(10, 10, 300, 230);
        frame.getContentPane().add(table_pane);

        new_table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

                c.setBackground(getColor(value.toString()));
                return c;
            }
        });
        frame.pack();
        frame.setVisible(true);
    }

    private static Color getColor(String color) {
        switch (color) {
            case "red":
                return Color.RED;
            default:
                return Color.white;
        }

    }

}

结果是下一个