Can I modify JComboBox popup background color of an existing object?

大憨熊 提交于 2019-12-07 06:27:26

问题


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?

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.


回答1:


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().

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:


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




回答3:


Have you tried:

comboBox.setBackground(color);


来源:https://stackoverflow.com/questions/4162980/can-i-modify-jcombobox-popup-background-color-of-an-existing-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!