Multiple cell renderers for a column in a JTable?

前端 未结 2 771
难免孤独
难免孤独 2021-01-14 16:52

Let\'s say I have the following JTable, which is displayed as soon as a button is pressed:

      | Name
------+------------
True  | Hello World
False | Foo B         


        
相关标签:
2条回答
  • 2021-01-14 16:53

    Store Boolean.TRUE for the true values. Then store an empty String for the false values. You will then need to:

    a) override the getCellRenderer(...) method to return the appropriate renderer for the data found in the cell.

    b) make the cells containing the empty string non-editable:

    JTable table = new JTable(data, columnNames)
    {
        public TableCellRenderer getCellRenderer(int row, int column)
        {
            if (column == 0)
            {
                Class cellClass = getValueAt(row, column).getClass();
                return getDefaultRenderer( cellClass );
            }
    
            return super.getCellRenderer(row, column);
        }
    
        public boolean isCellEditable(int row, int column)
        {
            Class cellClass = getValueAt(row, column).getClass();
    
            if (column == 0 && cellClass instanceof Boolean)
            {
                return true;
            }
            else
            {
                return false;
            }
    
            return super.isCellEditable(row, column);
        }
    
    };
    

    Using this approach there is no need for custom renderers or editors.

    0 讨论(0)
  • 2021-01-14 17:14

    Have getTableCellRendererComponent return a blank JLabel if the initial value was false.

    0 讨论(0)
提交回复
热议问题