jtable cellrenderer changes backgroundcolor of cells while running

后端 未结 1 369
天涯浪人
天涯浪人 2020-12-03 23:58

I\'m trying to create a table and color specific cells either yellow, red or white, depending on the content of other columns. For that I am looping through the rows filling

相关标签:
1条回答
  • 2020-12-04 00:35

    Do not update table data in your CutomRenderer class. You Renderer class should check the condition and color the cells. I have used your CustomRenderer class and rendered the cells basing on the data present in the cells. If the data of the cell is 'Y' color it to Yellow. If the data is 'N' then color it to Grey.

    Rendering in JTable

    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 ColoringCells {
    
        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(table.getValueAt(row, column).equals("Y")){
                cellComponent.setBackground(Color.YELLOW);
            } else if(table.getValueAt(row, column).equals("N")){
                cellComponent.setBackground(Color.GRAY);
            }
            return cellComponent;
        }
    }
    
    0 讨论(0)
提交回复
热议问题