0

我有一个方法应该改变一个特定的单元格 ia JTable 的颜色,但是所有的单元格都会改变颜色。

这是我试图实现的方法:

public Component cellBG(JTable table, int row, int column)
{
    TableCellRenderer renderer = table.getCellRenderer(row, column);
    Component c = table.prepareRenderer(renderer, row, column);

    Object steak = table.getValueAt(row,column);

    if(((String) steak).startsWith("+"))
    {
       c.setBackground(Color.GREEN);
    }
    else if(((String) steak).startsWith("-"))
    {
        c.setBackground(Color.RED);
    }
    else if(((String) steak).startsWith("~"))
    {
        c.setBackground(Color.YELLOW);
    }
    else if(((String) steak).equals(""))
    {
        c.setBackground(Color.WHITE);
    }

    return c;

}

我的表包含 10 列,每行 8 行都包含 +、-、~ 或“”,这应该会导致不同颜色的分散图案,但是在读取的最后一个条目中,表格是纯色的。

根据请求提供 SSCCE

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;

public class ptf_viewer extends JFrame {

    static JTable table;
    static DefaultTableModel model;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ptf_viewer frame = new ptf_viewer();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }); 
    }

    public ptf_viewer(){
    getContentPane().setBackground(Color.WHITE);
    setTitle("Portable test file viewing");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(50, 50, 1024, 768);
    getContentPane().setLayout(null);

    final String[] columnNames = {"Test 1", "Test 2", "Test 3", "Test 4", "Test 5", "Test 6", "Test 7", "Test 8", "Test 9", "Test 10"};
    final Object[][] data = {
                {"+","+","","","","~","","","",""},
                {"-","+","","","","","","","",""},
                {"+","+","","","~","","","","",""},
                {"+","+","","","","","~","","",""},
                {"+","-","","~","","","","","",""},
                {"+","-","","","","","","","",""},
                {"+","-","","","","","","","",""},
                {"-","+","~","","","","","","","+"}
    };
    model = new DefaultTableModel(data, columnNames);
    table = new JTable(data, columnNames);
    table.setModel(model);
    for(int i = 0 ; i < 8 ; i++){
            cellBG(table, i, 9);
    }
    JTableHeader header = table.getTableHeader();
    header.setFont(new Font("Times New Roman", Font.BOLD, 13));
    header.setBackground(Color.black);
    header.setForeground(Color.white);

    JScrollPane scrollPane = new JScrollPane(table);
    scrollPane.setSize(988, 618);
    scrollPane.setFont(new Font("Times New Roman", Font.BOLD, 13));
    scrollPane.setLocation(10, 60);
    getContentPane().add(scrollPane);
    }
    public Component cellBG(JTable table, int row, int column)
    {
        TableCellRenderer renderer = table.getCellRenderer(row, column);
        Component c = table.prepareRenderer(renderer, row, column);

        Object bøf = table.getValueAt(row,column);

        if(((String) bøf).startsWith("+"))
        {
           c.setBackground(Color.GREEN);
        }
        else if(((String) bøf).startsWith("-"))
        {
            c.setBackground(Color.RED);
        }
        else if(((String) bøf).startsWith("~"))
        {
            c.setBackground(Color.YELLOW);
        }
        else if(((String) bøf).equals(""))
        {
            c.setBackground(Color.WHITE);
        }
        return c;
    }
    }
4

2 回答 2

3

abbisDK 写道 - SSCCE 制作并添加到问题中,

  • 通过使用DefaultTableCellRenderer和查看Pattern.compile(其中一种方式,Strin.equals() 或 String.startWith,包含是另一种非常简单的方式)

  • 一样,所以非常相似的代码可以用于prepareRenderer

.

table = new JTable(data, columnNames) {
   //logics place for prepareRenderer
};

在此处输入图像描述

从代码

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.util.regex.Pattern;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;

public class Ptf_Viewer {

    private JFrame frame = new JFrame("Portable test file viewing");
    private JTable table;
    private final String[] columnNames = {"Test 1", "Test 2", "Test 3", "Test 4",
        "Test 5", "Test 6", "Test 7", "Test 8", "Test 9", "Test 10"};
    private final Object[][] data = {
        {"+", "+", "", "", "", "~", "", "", "", ""},
        {"-", "+", "", "", "", "", "", "", "", ""},
        {"+", "+", "", "", "~", "", "", "", "", ""},
        {"+", "+", "", "", "", "", "~", "", "", ""},
        {"+", "-", "", "~", "", "", "", "", "", ""},
        {"+", "-", "", "", "", "", "", "", "", ""},
        {"+", "-", "", "", "", "", "", "", "", ""},
        {"-", "+", "~", "", "", "", "", "", "", "+"}
    };
    private DefaultTableModel model = new DefaultTableModel(data, columnNames);

    public Ptf_Viewer() {
        table = new JTable(data, columnNames) {
            //logics place for prepareRenderer
        };
        table.setModel(model);
        table.setPreferredScrollableViewportSize(
                new Dimension(800, table.getPreferredSize().height));
        JTableHeader header = table.getTableHeader();
        header.setFont(new Font("Times New Roman", Font.BOLD, 13));
        header.setBackground(Color.black);
        header.setForeground(Color.white);
        for (int i = 0; i < table.getColumnCount(); i++) {
            RowColorRenderer rowRenderer = new RowColorRenderer(i);
            TableColumn column = table.getColumnModel().getColumn(i);
            column.setCellRenderer(rowRenderer);
        }
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setFont(new Font("Times New Roman", Font.BOLD, 13));
        frame.add(scrollPane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(50, 50);
        frame.pack();
        frame.setVisible(true);
    }

    private class RowColorRenderer extends DefaultTableCellRenderer {

        private static final long serialVersionUID = 1L;
        private int colNo = 0;

        RowColorRenderer(int col) {
            colNo = col;
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            Component comp = super.getTableCellRendererComponent(table, value,
                    isSelected, hasFocus, row, column);
            JComponent jc = (JComponent) comp;
            if (!isSelected) {
                if (table.getValueAt(row, colNo) != null) {
                    String str = table.getValueAt(row, colNo).toString();
                    if (!str.isEmpty()) {
                        if ((Pattern.compile("[+]").matcher(str).find())) {
                            setForeground(Color.magenta);
                            setBackground(Color.GREEN);
                            setFont(new Font("Serif", Font.BOLD, 16));
                            setHorizontalAlignment(CENTER);
                        } else if ((Pattern.compile("[-]").matcher(str).find())) {
                            setForeground(Color.blue);
                            setBackground(Color.RED);
                            setFont(new Font("Serif", Font.BOLD, 16));
                            setHorizontalAlignment(CENTER);
                        } else if ((Pattern.compile("[~]").matcher(str).find())) {
                            setForeground(Color.red);
                            setBackground(Color.YELLOW);
                            setFont(new Font("Serif", Font.BOLD, 16));
                            setHorizontalAlignment(CENTER);
                        } else {
                            setBackground(Color.WHITE);
                            setForeground(table.getForeground());
                            setFont(new Font("Serif", Font.PLAIN, 12));
                            setHorizontalAlignment(CENTER);
                        }
                    } else {
                        setBackground(Color.WHITE);
                        setForeground(table.getForeground());
                    }
                }
            }
            return this;
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                Ptf_Viewer frame = new Ptf_Viewer();
            }
        });
    }
}
于 2013-07-31T13:38:48.260 回答
2

您将需要创建自己的单元格渲染器并让它根据单元格中包含的文本返回正确的背景颜色。

public class MyTableCellRenderer extends DefaultTableCellRenderer {
    @Override
    public Color getBackground() {
        String steak = getText();
        if (steak.startsWith("+")) {
            return Color.GREEN;
        } else if (steak.startsWith("-")) {
            return Color.RED;
        } else if (steak.startsWith("~")) {
            return Color.YELLOW;
        } else if (steak.equals("")) {
            return Color.WHITE;
        }

            return super.getBackground();
        }
    }
}

并确保您的桌子使用它。

table.setDefaultRenderer(String.class, new MyTableCellRenderer());

假设这里所有单元格的类型是String.

在 SSCCE 之后编辑:类是Obejct和不是String,使用

table.setDefaultRenderer(Object.class, new MyTableCellRenderer());
于 2013-07-31T12:05:33.490 回答