• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to add 2 columns in a JComboBox  RSS feed

 
tina sow
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I'm looking for examples , to learn how to add columns in a jcombobox (example: an id and a name)
Thanks for your help.
Tina sow
 
Bhagya Tangutur
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess you can achieve this by setting renderer for the comboBox by calling setCellRenderer() method and pass your Own Renderer which is subClass of Panel,put Proper Layout in the Panel,so that it look like Tow Columns.
for Example:
Here i am assuming you have Person Objects added to ComboBox.and Person class has Methods getName() and getID()
I Haven't checked compiling it.Please help your self.this is just an Idea so that you can proceed.
Try adding some glue or struts for better visibility
class MyCellRenderer extends JPanel implements ListCellRenderer {
JLabel lbl1=new JLabel();
JLabel lbl2=new JLabel();
public MyCellRenderer() {
setLayout(new BoxLayout(this,BoxLayout.x_Axis));
add(lbl1);
add(lbl2);
}

public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
Person person=(Person)Value;
lbl1.setText(person.getName());
lbl2.setText(person.getID());
return this;
}
}
 
Sri Rangan
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instead of creating your own renderer, you could also modify the toString() method of Person Object method to return the name and ID.
 
Bhagya Tangutur
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sri Rangan:
Instead of creating your own renderer, you could also modify the toString() method of Person Object method to return the name and ID.

This approach will work fine,if you are no longer looking alignment of Lables(As two Columns).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!