将背景图像添加到JComboBox

时间:2017-08-20 12:43:07

标签: java image background 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组合框的背景?

1 个答案:

答案 0 :(得分:0)

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

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;
    }
}