更改JComboBox箭头的背景颜色

时间:2011-01-03 17:11:46

标签: java swing jcombobox

我找到了以下solution for changing a JComboBox arrow's color

For JComboBox and Metal L&F
-- iterate recursively over the components of the JComboBox and grab a reference 
   to the button of class javax.swing.plaf.metal.MetalComboBoxButton
-- get the icon by getComboIcon()
-- create a BufferedImage (type ARGB) the size of the icon
-- paintIcon the icon to the Graphics context of the BufferedImage
-- iterate over the pixels of the BufferedImage and change any non-zero pixels 
   (by getRGB) to the color you want (by setRGB).
-- construct a new ImageIcon from the image
-- set the new icon to the button by setComboIcon

你究竟如何“将图标绘制到BufferedImage的图形上下文”?

2 个答案:

答案 0 :(得分:2)

像这样:

    int componentCount = comboBox.getComponentCount();
    for (int i = 0; i < componentCount; i++) {
        Component component = comboBox.getComponent(i);
        if (component instanceof MetalComboBoxButton) {
            MetalComboBoxButton metalComboBoxButton =
                (MetalComboBoxButton) component;
            Icon comboIcon = metalComboBoxButton.getComboIcon();
            BufferedImage bufferedImage =
                new BufferedImage(
                    comboIcon.getIconWidth(),
                    comboIcon.getIconHeight(),
                    BufferedImage.TYPE_INT_ARGB);
            comboIcon.paintIcon(
                metalComboBoxButton, bufferedImage.getGraphics(), 0, 0);
        }
    }

答案 1 :(得分:1)

作为替代方案,请考虑在ComboBoxUI中使用BasicArrowButton的自定义实例,如此example所示。