1

To put object inside JComboBox we do like this:

while(result.next()){
    int id=rs.getInt("id");
    String name=rs.getString("name");
    Object[] itemData = new Object[] {id, name};
    jComboBox1.addItem(itemData);
}

I need the combo box to show only the itemData.name and to store the whole object inside the jcombobox
Is there an appropriate way?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mohammed Ali
  • 1,117
  • 1
  • 16
  • 31
  • Use a [combo box with a custom renderer](https://stackoverflow.com/questions/tagged/jcombobox+listcellrenderer). See [this answer](https://stackoverflow.com/questions/6965038/getting-fonts-sizes-bold-etc/6965149#6965149) for an example using an array of font family names (they could just as easily been a `Font[]` of your POJO). Make a POJO out of the `Object[] itemData` .. – Andrew Thompson Jan 05 '20 at 07:46

1 Answers1

0

You can create your own customComboBox.
Save there what ever you wanted and display the same.

Eg:

public class CustomCB {
JFrame f;    
CustomCB(){    
    f=new JFrame("Custom ComboBox");    

    List<MyObj> l = new ArrayList<>();
    l.add(new MyObj("value1",1));
    l.add(new MyObj("value2",2));
    l.add(new MyObj("value3",3));

    MyCB cb=new MyCB(l); 

    for(MyObj obj: cb.l)
    {
        System.out.println(obj.s+":"+obj.i);
    }

    cb.setBounds(50, 50,90,20);    
    f.add(cb); 
    f.setLayout(null);    
    f.setSize(400,500);    
    f.setVisible(true);         
}  

class MyObj
    {
        String s;
        int i;
        MyObj(String s, int i)
        {
            this.s=s;
            this.i=i;
        }
    }

class MyCB extends JComboBox<String>
{
    List<MyObj> l;
    MyCB(List<MyObj> l)
    {
        super();
        this.l = l;
        for(MyObj obj:l)
        {
            this.addItem(obj.s);
        }
    }
} 
}
Traian GEICU
  • 1,750
  • 3
  • 14
  • 26