如何在jtable中使不可编辑的单元格变灰?
我想在JTable中灰化不可编辑的单元格。
我正在使用这样的TableCellRenderer:
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?
在 TableCellEditor
中返回 GrayableCheckboxCellRenderer
的实例。
附录:在美学上,您可能希望根据默认值由当前的Look&感觉,例如:
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");