java 在 JComboBox 中显示图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3958647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:09:17  来源:igfitidea点击:

displaying images in JComboBox

javajcombobox

提问by Lalchand

i need to display a image in JComboBox

我需要在 JComboBox 中显示图像

回答by camickr

Just add an Icon to the model instead of a String:

只需向模型添加一个图标而不是字符串:

import java.awt.*;
import javax.swing.*;

public class ComboBoxIcon extends JFrame
{
    JComboBox comboBox;

    public ComboBoxIcon()
    {
        Object[] items =
        {
            new ImageIcon("about16.gif"),
            new ImageIcon("add16.gif"),
            new ImageIcon("copy16.gif")
        };
        comboBox = new JComboBox( items );
        getContentPane().add( comboBox, BorderLayout.NORTH );
    }

    public static void main(String[] args)
    {
        JFrame frame = new ComboBoxIcon();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
    }
}

回答by Codemwnci

Take a look at this example that appears to do what you want.

看看这个例子,它似乎可以做你想做的事。

http://www.java2s.com/Code/Java/Swing-JFC/CustomComboBoxwithImage.htm

http://www.java2s.com/Code/Java/Swing-JFC/CustomComboBoxwithImage.htm

What you are looking for is a custom renderer for the JComboBox. A renderer is simply a JComponent, so if you can create a component (JPanel with the necessary items contained), then you can create almost any result that you can think of). You can even override the paint method if using standard JComponents are not enough for you.

您正在寻找的是 JComboBox 的自定义渲染器。渲染器只是一个 JComponent,因此如果您可以创建一个组件(包含必要项的 JPanel),那么您几乎可以创建您能想到的任何结果)。如果使用标准 JComponents 对您来说还不够,您甚至可以覆盖 Paint 方法。