如何根据它们的值更改特定JTable单元格的背景颜色?

时间:2016-12-04 12:41:57

标签: java swing jtable tablecellrenderer tablemodel

如果它们的值等于Kathy或Jane,我如何将第一列中单元格的背景着色为红色。

在我的解决方案中,第一列中的每个单元格都涂成红色,但如果我将其他单元格变为绿色,则一切正常。但我想让他们的背景默认,因为我只想标记特定的细胞。

package com.myswingtest;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;

import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;

public class SimpleTableDemo extends JPanel {

    public SimpleTableDemo() {
        super(new GridLayout(1,0));

        String[] columnNames = {"First Name","Last Name"};
        Object[][] data = {
            {"Kathy", "Black",},
            {"John", "Doe",},
            {"Jane", "Smith",},
            {"Rob", "White",},
            {"Joe", "Smith",}
        };

        final JTable table = new JTable(data, columnNames);

        DefaultTableCellRenderer statusCellRenderer = new DefaultTableCellRenderer() {      
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
                JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                int modelRow = table.convertRowIndexToModel(row);
                TableModel tableModel = table.getModel();
                // Lets color only the cells in the first column what equals Kathy or Jane
                if("Kathy".equals(tableModel.getValueAt(modelRow, 0)) 
                        || "Jane".equals(tableModel.getValueAt(modelRow, 0))){
                    System.out.println("SETTING COLOR TO RED IN ROW: " + modelRow);
                    l.setBackground(Color.RED);
                } else {
                    // If I uncomment this line, the other lines became green. But I want their background stay default.
                    //l.setBackground(Color.GREEN);
                }
                return l;
            }
        };
        // Setting cellrenderer for first column
        table.getColumnModel().getColumn(0).setCellRenderer(statusCellRenderer);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("SimpleTableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new SimpleTableDemo());
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

0 个答案:

没有答案