简体   繁体   English

如何更改JTable中已编辑单元格的背景颜色?

[英]How to change background color of an edited cell in JTable?

I searched everywhere but I still can't seem to find an answer to my question. 我到处搜索,但似乎仍然找不到我的问题的答案。 I've read all about cell renderers and cell editors but still no idea... I have a JTable, and I want to make sure that the users clearly see which cell they are editing. 我已经阅读了有关单元格渲染器和单元格编辑器的所有内容,但还是不知道...我有一个JTable,我想确保用户清楚地看到他们正在编辑哪个单元格。 by default, the edited cell in JTable gets a darker border, but i would like to make the background green. 默认情况下,JTable中的已编辑单元格会获得较暗的边框,但是我想将背景设置为绿色。 I can make it green when selected, but as soon as I start entering data, the green background disappears and I'm writing into a white cell. 选中后可以将其设置为绿色,但是一旦我开始输入数据,绿色背景就会消失,而我正在写入一个白色单元格。

Could you please help me find a way to keep the background of a cell green even while entering data? 您能帮我找到一种即使在输入数据时也保持单元格背景为绿色的方法吗?

First, get the table's default selection background color: 首先,获取表格的默认选择背景颜色:

Color color = UIManager.getColor("Table.selectionBackground");

Second, override prepareEditor() , as shown in this example , and set the background color of the editor component to match: 其次,覆盖此示例中所示的prepareEditor() ,并将编辑器组件的背景色设置为匹配:

@Override
public Component prepareEditor(TableCellEditor editor, int row, int col) {
    Component c = super.prepareEditor(editor, row, col);
    c.setBackground(color);
    return c;
}

Addendum: While technically correct, note that the editor component's color is typically managed by the corresponding UI delegate while active. 附录:在技术上正确无误,但请注意,编辑器组件的颜色通常在激活时由相应的UI委托管理。 An unfortunate choice may result in poor contrast and impaired usability. 不幸的选择可能会导致对比度差和可用性受损。 Thorough testing on target Look & Feels is warranted. 必须对目标外观进行彻底测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM