将背景图像添加到 JComboBox

adding background image to JComboBox

我有这个程序,我想为我的 comboBox 添加背景图片。 我试了很多方法都做不到,请问有人帮忙吗?

class myClass
{

    public static void main(String args[])
    {
    JFrame myFrame = new JFrame();
    myFrame.setBounds(500,500,500,500);
    myFrame.setLayout(null);
    myFrame.setVisible(true);

    JComboBox myComboBox = new JComboBox();
    myComboBox.setBounds(100,100,100,20);
    myComboBox.add("item1");
    myComboBox.add("item2");
    myComboBox.setVisible(true);

    Image comboBoxImage = new ImageIcon(
        myClass.class.getResources("/Image.png")).getImage();
    }

}

如何将 comboBoxImage 设置为 myComboBox 组合框的背景?

您可以使用以下方法为您的组合框设置自定义渲染器:

myComboBox.setRenderer(...);

渲染器的可能实现可能是:

class BackgroundRenderer extends JLabel implements ListCellRenderer<String> {
    private final Image image;

    public BackgroundRenderer(Image image) {
        this.image = image;
    }

    @Override
    protected void paintComponent(Graphics g) {
        g.drawImage(image, 0, 0, this);

        super.paintComponent(g);
    }

    @Override
    public Component getListCellRendererComponent(JList<? extends String> list, String value, int index,
            boolean isSelected, boolean cellHasFocus) {
        setText(value);

        return this;
    }
}