Change the background color of a row in a JTable

前端 未结 5 1175
我寻月下人不归
我寻月下人不归 2020-11-30 10:09

I have a JTable with 3 columns. I\'ve set the TableCellRenderer for all the 3 columns like this (maybe not very effective?).

 for (int i = 0; i          


        
5条回答
  •  离开以前
    2020-11-30 10:38

    This is basically as simple as repainting the table. I haven't found a way to selectively repaint just one row/column/cell however.

    In this example, clicking on the button changes the background color for a row and then calls repaint.

    public class TableTest {
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            final Color[] rowColors = new Color[] {
                    randomColor(), randomColor(), randomColor()
            };
            final JTable table = new JTable(3, 3);
            table.setDefaultRenderer(Object.class, new TableCellRenderer() {
                @Override
                public Component getTableCellRendererComponent(JTable table,
                        Object value, boolean isSelected, boolean hasFocus,
                        int row, int column) {
                    JPanel pane = new JPanel();
                    pane.setBackground(rowColors[row]);
                    return pane;
                }
            });
            frame.setLayout(new BorderLayout());
    
            JButton btn = new JButton("Change row2's color");
            btn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    rowColors[1] = randomColor();
                    table.repaint();
                }
            });
    
            frame.add(table, BorderLayout.NORTH);
            frame.add(btn, BorderLayout.SOUTH);
            frame.pack();
            frame.setVisible(true);
        }
    
        private static Color randomColor() {
            Random rnd = new Random();
            return new Color(rnd.nextInt(256),
                    rnd.nextInt(256), rnd.nextInt(256));
        }
    }
    

提交回复
热议问题