Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

java - How to gray-out non-editable cell in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...