在JTable单元格上编辑无效

时间:2018-11-28 13:32:26

标签: java swing jtable cell background-color

我想突出显示JTable中的某些单元格并进行了必要的更改,但是程序看不到它们。

在调试代码时,我注意到程序渲染了表,但没有进入if语句。

如果有人能告诉我出了什么问题,那将很好。

    public class Frame extends JFrame {

        private JPanel contentPane;
        private static JTable table;
        final DefaultTableModel model;

    String data[][] = { {"E","S","M","I","S","T","P","G","L","E","I","C","H","Y","M"},
        {"G","H","J","K","F","K","N","F","Z","I","G","W","X","Z","T"} };

        String[] columns =  "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" };

    public static void main(String[] args) {
        try {
            Frame frame = new Frame();
            centerWindow(frame);
            frame.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        } }
//build the frame
        public Frame() {
        model = new DefaultTableModel();
        setBackground(Color.LIGHT_GRAY);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 570, 570);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

//build the table               
        table = new JTable();
        JTable table = new JTable(data, columns);
        table.setBackground(Color.LIGHT_GRAY);
        table.setFont(new Font("Verdana", Font.PLAIN, 14));
        table.setSize(800, 400);
        table.setRowHeight(30);
        table.setForeground(Color.WHITE);
        contentPane.add(table, BorderLayout.CENTER);

        //in this part, the program should change the color of certain cells ... but it does not :-(
        table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
//highlight the cells with the value "s"
                    if (value instanceof String) {
                        if (value.equals("s")){
                            System.out.println(row + " " + column);
                            cell.setBackground(Color.BLUE);} else {
                            cell.setBackground(Color.WHITE);}  }  
            return cell;
            }  
        });  
    }  

1 个答案:

答案 0 :(得分:1)

更改行:

if (value.equals("s")){

if (value.equals("S")){

等于区分大小写。