Cell Renderer for JTable - coloured rows

后端 未结 4 1914
太阳男子
太阳男子 2021-01-23 09:58

I\'ve been looking around for a solution to this and I can\'t make head nor tail from various places of how to get my table to do coloured rows without asking my own question.

4条回答
  •  执笔经年
    2021-01-23 10:12

    JTable Cell Coloring

    import java.awt.Color;
    import java.awt.Component;
    import java.awt.EventQueue;
    
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    
    
    public class RowRendering {
    
        private static Object[] columnName = {"Yes", "No"};
        private static Object[][] data = {
                {"Y", "N"},
                {"N", "Y"},
                {"Y", "N"}
        };
    
    
        public static void main(String[] args) {
            Runnable r = new Runnable() {
    
                @Override
                public void run() {
    
                    JFrame frame = new JFrame();
                    JTable table = new JTable(data, columnName);
                    table.getColumnModel().getColumn(0).setCellRenderer(new CustomRenderer());
                    table.getColumnModel().getColumn(1).setCellRenderer(new CustomRenderer());
    
                    frame.add(new JScrollPane(table));
                    frame.setTitle("Rendering in JTable");
                    frame.pack();
                    frame.setVisible(true);
                }
            };
    
            EventQueue.invokeLater(r);
        }
    }
    
    
    class CustomRenderer extends DefaultTableCellRenderer 
    {
    private static final long serialVersionUID = 6703872492730589499L;
    
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
        {
            Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    
            if(row == 0){
                cellComponent.setBackground(Color.YELLOW);
            } else if ( row == 1){
                cellComponent.setBackground(Color.GRAY);
            } else {
                cellComponent.setBackground(Color.CYAN);
            }
            return cellComponent;
        }
    }
    

提交回复
热议问题