java 不可编辑的 JComboBox 中所选项目的背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4412902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:15:11  来源:igfitidea点击:

Background color of the selected item in an uneditable JComboBox

javaswingjcombobox

提问by Paul Reiners

The background color of the selected item in an uneditable JComboBox is a sort of blue:

不可编辑的 JComboBox 中所选项目的背景颜色是一种蓝色:

alt text

alt text

Is there any way to make this a different color, such as white, for example?

有没有办法让它变成不同的颜色,例如白色?

回答by Costis Aivalis

This should work

这应该工作

jComboBox1.setRenderer(new DefaultListCellRenderer() {
    @Override
    public void paint(Graphics g) {
        setBackground(Color.WHITE);
        setForeground(Color.BLACK);
        super.paint(g);
    }
});

回答by camickr

The background assigned by the renderer is overriden by the selection background color of the JList that is used in the popup for the combo box. Check out the "paintCurrentValue" method of the BasicComboBoxUI class. So the workaround would be:

渲染器分配的背景被组合框弹出窗口中使用的 JList 的选择背景颜色覆盖。查看 BasicComboBoxUI 类的“paintCurrentValue”方法。所以解决方法是:

JComboBox comboBox = new JComboBox(...);
Object child = comboBox.getAccessibleContext().getAccessibleChild(0);
BasicComboPopup popup = (BasicComboPopup)child;
JList list = popup.getList();
list.setSelectionBackground(Color.RED);

This will affect the rendering of the popup as well. If you don't want it to affect the popup then you will need to create a custom renderer to specifically set the background of selected items.

这也会影响弹出窗口的呈现。如果您不希望它影响弹出窗口,那么您将需要创建一个自定义渲染器来专门设置所选项目的背景。

回答by aioobe

Have you tried writing your own, custom, ListCellRenderer?

您是否尝试过编写自己的自定义文件ListCellRenderer

When that method is asked to provide a cell-rendering component you get the following arguments:

当要求该方法提供单元格渲染组件时,您将获得以下参数:

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