2

I have a JComboBox with a list of elements. So what the program basically does is user select an element from the combo list and click a button to display the selected element in the text area.

Everything works perfect so far, but the problem is after user click the button I want the combo box to return back to the firs element and display the first element. How can I display the first element of the combo box...????

NathanChristie
  • 2,374
  • 21
  • 20
Sas
  • 2,473
  • 6
  • 30
  • 47

3 Answers3

9

Try JComboBox#setSelectedIndex(0).

Jeffrey
  • 44,417
  • 8
  • 90
  • 141
2

JComboBox implements two methods for set Item

comboBox.setSelectedIndex(int);

comboBox.setSelectedItem(Object);

more in the example

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • It's actually [`setSelectedItem(Object)`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html#setSelectedItem(java.lang.Object)). – Jeffrey Dec 03 '11 at 19:57
2

In the action listener you have to reset the selectedIndex of the comboBox to the first position after you have updated the text area with the selected value.

Sample code :

package com.mumz.test.swing;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.Border;


public class JComboBoxTest {
    private void init(){
        JPanel panel = new JPanel(new BorderLayout());
        Object[] values = new String[]{"One","Two","Three"};
        final JComboBox comboBox = new JComboBox(values);
        panel.add(comboBox, BorderLayout.NORTH);
        final JTextArea textArea = new JTextArea(2, 2);
        panel.add(textArea, BorderLayout.CENTER);
        JButton button = new JButton("Action");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.setText((String) comboBox.getSelectedItem()) ;
                comboBox.setSelectedIndex(0);
            }
        });
        panel.add(button, BorderLayout.SOUTH);
        JFrame frame = new JFrame();
        frame.add(panel);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new JComboBoxTest().init();
    }
}
Jeffrey
  • 44,417
  • 8
  • 90
  • 141
mprabhat
  • 20,107
  • 7
  • 46
  • 63