gpt4 book ai didi

java - 组合框单元格编辑器的背景颜色

转载 作者:太空宇宙 更新时间:2023-11-04 14:55:27 24 4
gpt4 key购买 nike

过去几天我一直在努力寻找解决方案,这让我发疯。我有一个表,其中我将选择颜色设置为黄色。我还将单元格编辑器组件的背景设置为黄色,以便在编辑单元格时颜色保持不变。我通过重写prepareEditor方法来做到这一点:

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

这对于所有列都工作正常,除了我在其中指定组合框作为单元格编辑器的列。一旦我开始编辑该列中的单元格,背景就会变成白色。弹出菜单中的背景颜色为黄色,但所选值框中的背景颜色仍为白色。我尝试向组合框添加焦点监听器,但我所能做的就是更改弹出项目的背景,而不是所选项目的背景。我尝试将焦点监听器添加到组合框本身,如下所示:

 myComboBox.addFocusListener(new FocusListener() {//code here});

以及编辑器组件:

myComboBox.getEditor().getEditorComponent().addFocusListener(new FocusListener() {//code    here});

但这些都不起作用。有人可以指出我做错了什么吗?谢谢。

最佳答案

您可能需要覆盖单元格渲染器。在 UI 管理器中使用它并根据您的喜好更改 paintComponent 方法。

public class MyComboBoxUI extends MetalComboBoxUI {

public MyComboBoxUI() {

}

public static ComponentUI createUI(JComponent c) {

return new MyComboBoxUI();
}

@Override
public void installUI(JComponent c) {

ListCellRenderer rend = new ListCellRenderer() {

public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {

final JLabel renderer = new JLabel(value.toString()) {

protected void paintComponent(java.awt.Graphics g) {

UIDefaults uid = UIManager.getDefaults();
Graphics2D g2d = (Graphics2D)g;
Dimension d = this.getSize();
g2d.setPaint(new GradientPaint(0, 0, Color.red, 0, d.height, Color.orange, true));
g2d.fillRect(0, 0, d.width, d.height);
super.paintComponent(g);
}
};
renderer.setOpaque(false);
return renderer;
}
};
super.installUI(c);
((JComboBox)c).setRenderer(rend);
}
}

关于java - 组合框单元格编辑器的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23269731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com