繁体   English   中英

将背景图像添加到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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM