[ACCEPTED]-JComboBox setting label and value-jcombobox

Accepted answer
Score: 30

You can put any object inside of a JComboBox. By 5 default, it uses the toString method of 4 the object to display a label navigate in 3 the combo box using the keyboard. So, the 2 best way is probably to define and use appropriate 1 objects inside the combo :

public class ComboItem {
    private String value;
    private String label;

    public ComboItem(String value, String label) {
        this.value = value;
        this.label = label;

    public String getValue() {
        return this.value;

    public String getLabel() {
        return this.label;

    public String toString() {
        return label;
Score: 9

Here's a utility interface and class that 18 make it easy to get a combo box to use different 17 labels. Instead of creating a replacement 16 ListCellRenderer (and risking it looking out of place if 15 the look-and-feel is changed), this uses 14 the default ListCellRenderer (whatever that may be), but 13 swapping in your own strings as label text 12 instead of the ones defined by toString() in your 11 value objects.

public interface ToString {
    public String toString(Object object);

public final class ToStringListCellRenderer implements ListCellRenderer {
    private final ListCellRenderer originalRenderer;
    private final ToString toString;

    public ToStringListCellRenderer(final ListCellRenderer originalRenderer,
            final ToString toString) {
        this.originalRenderer = originalRenderer;
        this.toString = toString;

    public Component getListCellRendererComponent(final JList list,
            final Object value, final int index, final boolean isSelected,
            final boolean cellHasFocus) {
        return originalRenderer.getListCellRendererComponent(list,
            toString.toString(value), index, isSelected, cellHasFocus);


As you can see the ToStringListCellRenderer gets a 10 custom string from the ToString implementation, and 9 then passes it to the original ListCellRenderer instead 8 of passing in the value object itself.

To 7 use this code, do something like the following:

// Create your combo box as normal, passing in the array of values.
final JComboBox combo = new JComboBox(values);
final ToString toString = new ToString() {
    public String toString(final Object object) {
        final YourValue value = (YourValue) object;
        // Of course you'd make your own label text below.
        return "custom label text " + value.toString();
combo.setRenderer(new ToStringListCellRenderer(
        combo.getRenderer(), toString)));

As 6 well as using this to make custom labels, if 5 you make a ToString implementation that creates 4 strings based on the system Locale, you 3 can easily internationalize the combo box 2 without having to change anything in your 1 value objects.

Score: 6

Please, can show me a full example?

Instances 3 of Enum are particularly convenient for this, as 2 toString() "returns the name of this enum constant, as 1 contained in the declaration."

enter image description here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see http://stackoverflow.com/questions/5661556 */
public class ColorCombo extends JPanel {

    private Hue hue = Hue.values()[0];

    public ColorCombo() {
        this.setPreferredSize(new Dimension(320, 240));
        final JComboBox colorBox = new JComboBox();
        for (Hue h : Hue.values()) {
        colorBox.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                Hue h = (Hue) colorBox.getSelectedItem();

    private enum Hue {

        Cyan(Color.cyan), Magenta(Color.magenta), Yellow(Color.yellow),
        Red(Color.red), Green(Color.green), Blue(Color.blue);

        private final Color color;

        private Hue(Color color) {
            this.color = color;

        public Color getColor() {
            return color;

    private static void display() {
        JFrame f = new JFrame("Color");
        f.add(new ColorCombo());

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
Score: 1

Use ListCellRenderer to achieve what you want. Make a class 4 that extends JLabel and implements ListCellRenderer. Set that 3 class as a renderer in your JComboBox using setRenderer() method. Now 2 when you access values from your jcombobox 1 it will be of type jlabel.

Score: 0

Step 1 Create a class with the two properties 10 of the JComboBox, id, name for example

public class Product {
    private int id;
    private String name;

    public Product(){


    public Product(int id, String name){        
        this.id = id;
        this.name = name;

    public int getId() {
        return id;

    public void setId(int id) {
        this.id = id;
    //this method return the value to show in the JComboBox
    public String toString(){
       return name;


Step 2 In the design 9 of the form, right click in the JComboBox and select 8 Properties, now open the code tab and in 7 the property Type Parameters write the name 6 of the class, in our example it is Product.

enter image description here

Step 3 Now 5 create a method that connects to the database 4 with a query to generate a list of products, this 3 method receives as a parameter a JComboBox object.

public void showProducts(JComboBox <Product> comboProduct){
    ResultSet res = null;
    try {
        Connection conn = new Connection();
        String query = "select id, name from products";
        PreparedStatement ps = conn.getConecction().prepareStatement(query);
        res = ps.executeQuery();
        while (res.next()) {
            comboProduct.addItem(new Product(res.getInt("id"), res.getString("name")));
    } catch (SQLException e) {
        System.err.println("Error showing the products " + e.getMessage());


Step 4 You 2 can call the method from the form

public frm_products() {

    Product product = new Product(); 



Now you 1 can access the selected id using getItemAt method


More Related questions