i need to display a image in 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.
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 .
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? Combo boxes also generate item events, which are fired when any of the items' selection state changes.
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 );
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With