Discussion Locked

Can Comboboxes show multiple columns

0 helpful
4 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Hello,

I find comboboxes with multiple columns extremely useful. One might be using the combobox to store, say, an ID for some Product, but you want to show its name and other attributes in the combobox.

However, I have no idea how to implement this in Swing. Sure you have to implement some sort of ComboBoxModel, but how would you render more than one column?

If anyone has done this or seen it before I would appreciate it if they could tell me what the best line of approach is.

Thanks

Philip Sheppard

4 replies

by okujava

The best way would be, i think, to implement the ListCellRenderer as a JPanel with two (or more) JLabels and set the Renderer for JComboBox. I think you should implement a sort of Row-object, with two or more attributes (one for each column). I'm not sure whether there are any other ways to do that...

cheers

s.okujava

by okujava

I've just tried it. Looks like it's working, but not quite pretty... :) you'll need a bit more time to make it look prettier...
package tests;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class ComboTest extends JFrame{
private JComboBox jComboBox;
public ComboTest(){
jComboBox = new JComboBox();
jComboBox.addItem(new MyRowElement("1", "One"));
jComboBox.addItem(new MyRowElement("2", "Two"));
jComboBox.addItem(new MyRowElement("3", "Three"));
jComboBox.setRenderer(new MyRenderer());
getContentPane().setLayout(new FlowLayout());
getContentPane().add(jComboBox);
pack();
}
private class MyRenderer extends JPanel implements ListCellRenderer{
private JLabel firstCol;
private JLabel secCol;
public MyRenderer(){
this.setLayout(new GridLayout(1,2));
firstCol = new JLabel();
secCol = new JLabel();
firstCol.setBorder(BorderFactory.createLineBorder(Color.black));
secCol.setBorder(BorderFactory.createLineBorder(Color.black));
this.add(firstCol);
this.add(secCol);
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus){
if(value instanceof MyRowElement){MyRowElement elem = (MyRowElement)value;
firstCol.setText(elem.getFirstCol());
secCol.setText(elem.getSecCol());
return this;
}else{
return new JLabel(value.toString());
}
}
}
private class MyRowElement{
private String firstCol;
private String secCol;
public MyRowElement(String first, String second){
firstCol = first;
secCol = second;
}
public String getFirstCol(){
return firstCol;
}
public String getSecCol(){return secCol;
}
}
public static void main(String args[]) {
new ComboTest().show();
}
}

by shepps

Hey this was a great help!! It sort of seems obvious once you see it! Thanks alot! Oder soll ich sagen 'vielen Dank!'

This discussion is closed to new replies.