我可以修改现有对象的JComboBox弹出背景颜色吗?

时间:2023-01-29 12:23:51

I have an existing JComboBox object. I can modify many of its properties using the internal methods. However, I could not find similar methods to customize the popup's appearance - specifically, the popup's background color. I have an existing object, so I wish to use its existing methods/properties, not to write a dedicated class. Is this possible?

我有一个现有的JComboBox对象。我可以使用内部方法修改它的许多属性。但是,我找不到类似的方法来自定义弹出窗口的外观 - 特别是弹出窗口的背景颜色。我有一个现有的对象,所以我希望使用它现有的方法/属性,而不是写一个专用的类。这可能吗?

Note: this question is NOT the same as the linked question above (which incorrectly states that this question already has an answer): that question asked about the selected item's bgcolor (in the combobox's editbox); I am asking about the popup box's bgcolor.

注意:这个问题与上面的链接问题不同(错误地说明这个问题已经有了答案):该问题询问了所选项目的bgcolor(在组合框的编辑框中);我问的是弹出框的bgcolor。

3 个解决方案

#1


3  

As eugener said, using a custom ListCellRenderer is definitely the right way to do this. You just need to create a class that extends DefaultListCellRenderer. This default renderer extends JLabel so it couldn't be easier to understand! You just need to make a call to setBackground().

正如eugener所说,使用自定义ListCellRenderer绝对是正确的方法。您只需要创建一个扩展DefaultListCellRenderer的类。此默认渲染器扩展了JLabel,因此无法理解!你只需要调用setBackground()。

JComboBox combo = new JComboBox(new String[] { "A", "B", "C", "D" });
combo.setRenderer(new DefaultListCellRenderer() {
    public void paint(Graphics g) {
        setBackground(Color.YELLOW);
        setForeground(Color.RED);
        super.paint(g);
    }
});

#2


1  

You'd have to create a custom comboxbox renderer. More Information is here: http://download.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer

您必须创建自定义的comboxbox渲染器。更多信息请访问:http://download.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer

#3


0  

Have you tried:

你有没有尝试过:

comboBox.setBackground(color);

#1


3  

As eugener said, using a custom ListCellRenderer is definitely the right way to do this. You just need to create a class that extends DefaultListCellRenderer. This default renderer extends JLabel so it couldn't be easier to understand! You just need to make a call to setBackground().

正如eugener所说,使用自定义ListCellRenderer绝对是正确的方法。您只需要创建一个扩展DefaultListCellRenderer的类。此默认渲染器扩展了JLabel,因此无法理解!你只需要调用setBackground()。

JComboBox combo = new JComboBox(new String[] { "A", "B", "C", "D" });
combo.setRenderer(new DefaultListCellRenderer() {
    public void paint(Graphics g) {
        setBackground(Color.YELLOW);
        setForeground(Color.RED);
        super.paint(g);
    }
});

#2


1  

You'd have to create a custom comboxbox renderer. More Information is here: http://download.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer

您必须创建自定义的comboxbox渲染器。更多信息请访问:http://download.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer

#3


0  

Have you tried:

你有没有尝试过:

comboBox.setBackground(color);