Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

displaying images in JComboBox

Tags:

java

jcombobox

i need to display a image in JComboBox

like image 668
Lalchand Avatar asked Oct 18 '10 11:10

Lalchand


People also ask

What is the difference between JList and JComboBox?

A JComboBox is a component that displays a drop-down list and gives users options that we can select one and only one item at a time whereas a JList shows multiple items (rows) to the user and also gives an option to let the user select multiple items.

How does JComboBox work?

JComboBox is a part of Java Swing package. JComboBox inherits JComponent class . JComboBox shows a popup menu that shows a list and the user can select a option from that specified list . JComboBox can be editable or read- only depending on the choice of the programmer .

Which method is used to add items to JComboBox?

Creates a JComboBox with a default data model. The default data model is an empty list of objects. Use addItem to add items.

Which event gets generated when you select an item from a JComboBox?

Which event gets generated when you select an item from a JComboBox? Combo boxes also generate item events, which are fired when any of the items' selection state changes.


2 Answers

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 );
    }
}
like image 179
camickr Avatar answered Oct 27 '22 22:10

camickr


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

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.

like image 43
Codemwnci Avatar answered Oct 27 '22 20:10

Codemwnci