Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gray-out non-editable cell in jtable?

Tags:

java

swing

jtable

I want to gray non-editable cell in JTable. I'm using such TableCellRenderer:

TableColumn column = table.getColumnModel().getColumn(0);
column.setCellRenderer(new GrayableCheckboxCellRenderer());

public class GrayableCheckboxCellRenderer extends JCheckBox implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int vRowIndex, int vColIndex) {           
            boolean editable = isEditable(vRowIndex, vColIndex);
        setBackground(editable ? UIManager.getColor("Label.background") : Color.LIGHT_GRAY);
        setSelected((Boolean) value);
                if (isSelected) {
                    // TODO: cell (and perhaps other cells) are selected, need to highlight it
                }
        return this;
    }
    // perfomance
    protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {}
    public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
    public void revalidate() {}
    public void validate() {}
}

This works but with one annoying artefact: Initially "checkbox" is "left-arranged", when I press left mouse button it moves to "center-arranged" and when I release mouse button it moves back to "left-arranged".

How to avoid such annoying artefact and probably there are better simpler solution for my problem?

like image 453
Oleg Vazhnev Avatar asked Dec 28 '22 17:12

Oleg Vazhnev


1 Answers

Return an instance of GrayableCheckboxCellRenderer in a TableCellEditor.

Addendum: Aesthetically, you may want to condition the renderer's and editor's colors based on the defaults provided by the current Look & Feel, for example:

Color hilite = UIManager.getColor("Table.selectionBackground");
like image 193
trashgod Avatar answered Jan 09 '23 04:01

trashgod