Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTable set disabled checkbox look for uneditable cell

I have JTable with a boolean values column. Depending on the state stored in model I make some or all of them uneditable (model's isCellEditable() returns false). However this does not make the JTable boolean renderer to render the checkboxes as disabled for uneditable cell.

Is there a way how to achive this other than writing custom boolean renderer?

If I need to write my own renderer what class should I extend other than JCheckbox? I just simply need to disable the checkbox before rendering and do not want to implement all the rendering code and handle selected look and stuff.

like image 851
ps-aux Avatar asked Oct 19 '25 09:10

ps-aux


1 Answers

However this does not make the JTable boolean renderer to render the checkboxes as disabled for uneditable cell.

This is correct, because it's the default renderer's behavior: JCheckBox is uneditable but not disabled.

Is there a way how to achive this other than writing custom boolean renderer?

No, as far as I know.

If I need to write my own renderer what class should I extend other than JCheckbox?

It's not mandatory to extend any class to implement TableCellRenderer interface. You can perfectly have a JCheckBox as renderer's class member. Actually, composition is preferred over inheritance.

I just simply need to disable the checkbox before rendering and do not want to implement all the rendering code and handle selected look and stuff.

It's not that difficult and you can control what is happening. Consider the example below:

class CheckBoxCellRenderer implements TableCellRenderer {

    private final JCheckBox renderer;

    public CheckBoxCellRenderer() {
        renderer = new JCheckBox();
        renderer.setHorizontalAlignment(SwingConstants.CENTER);
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Color bg = isSelected ? table.getSelectionBackground() : table.getBackground();
        renderer.setBackground(bg);
        renderer.setEnabled(table.isCellEditable(row, column));
        renderer.setSelected(value != null && (Boolean)value);
        return renderer;
    }
}

See this Q&A for a related problem: JXTable: use a TableCellEditor and TableCellRenderer for a specific cell instead of the whole column

like image 197
dic19 Avatar answered Oct 21 '25 21:10

dic19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!