Get Value from JComboBox

Jason Amavisca picture Jason Amavisca · Oct 17, 2012 · Viewed 57.7k times · Source

I have JComboBox with 2 columns and I have JButton. When I click the JButton, I need to get the result of the JComboBox selected value from first column and seconds column separately...

How do I this?

Also: how do I set the header of that JComboBox ?

The Code:

 public class Combo extends JFrame implements ActionListener{
    private JComboBox combo = new JComboBox();
    private JButton button = new JButton();
    public Combo() {

        setLayout(new FlowLayout());
        combo.setRenderer(new render());

        add(combo);

        combo.addItem(new String[] {"1","bbb"});
        combo.addItem(new String[] {"2","ff"});
        combo.addItem(new String[] {"3","gg"});
        combo.addItem(new String[] {"4","ee"});

        add(button);
        button.addActionListener(this);
        pack();
    }


    public static void main(String[]args){
        new Combo().setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==button){
            System.out.println(combo.getSelectedItem());
        }
    }
}
class render extends JPanel implements ListCellRenderer{

    private JLabel label1 = new JLabel();
    private JLabel label2 = new JLabel();
    private JLabel label3 = new JLabel();
    private JLabel label4 = new JLabel();
    private JLabel label5 = new JLabel();

    public render() {
        setLayout(new GridLayout(2,5));
        add(label1);
        add(label2);   
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        String[] values = (String[]) value;
        label1.setText(values[0]);
        label2.setText(values[1]);
        if(index ==0){
            label1.setForeground(Color.red);
            label2.setForeground(Color.red);
        }else{
            label1.setForeground(Color.white);
            label2.setForeground(Color.white);
        }

        return this;
    }

}

Thanks.

Answer

tenorsax picture tenorsax · Oct 17, 2012

Your items are arrays of strings, so you can print the selected item as follows:

System.out.println(Arrays.toString((String[])combo.getSelectedItem()));

EDIT:

String[] selectedItem = (String[])combo.getSelectedItem();
for (int i = 0; i < selectedItem.length; i++){
    System.out.println(String.format("item %s = %s", i, selectedItem[i]));
}

Or shortly if all you need is the first item - (String[])combo.getSelectedItem())[0].