Java Swing - GUIs
TOPIC 03 – MORE ON COMPONENTS

 

LESSON NOTE - JCOMBOBOX

 

 

JCOMBOBOX CONSTRUCTOR

 

We create a JComboBox by specifying a String array that contains the data that will be inside the JComboBox.

 

     

   String[] data = {"apple", "orange", "banana", "pear"};

   JComboBox cb = new JComboBox(data);

 

After adding the JComboBox to the content pane, we get this:

 

 

SELECTED?

 

To know which text is selected, we use the getSelectedText() method.

 

     String s = cb.getSelectedItem();

 

To know the index of the text that is selected, we use the getSelectedIndex() method.

 

     int index = cb.getSelectedIndex();

 

ACTION LISTENER

 

We can add an action listener to the JComboBox.  After we do so, an event is triggered whenever the down arrow is clicked on and then one of the choices are picked.

 

ACTIONPERFORMED METHOD

 

To respond to an event, we check the source of the event.  If the event comes from the JComboBox, then we get the selected text or index.

 

public void actionPerformed(ActionEvent e)

{

   if (e.getSource() == cb)

   {

      System.out.println(cb.getSelectedItem());

   }

}

 

FULL CODE EXAMPLE

 

Here is a complete example that shows the concepts from above in action.

 

public class MyGUI extends JFrame implements ActionListener

{

   //datafields

   JComboBox cb;

    

   public MyGUI()

   {

        Container cp = this.getContentPane();

        cp.setLayout(new FlowLayout());

           

        String[] data = {"apple", "orange", "banana", "pear"};

        cb = new JComboBox(data);

        cb.addActionListener(this);

        cp.add(cb);

 

        this.setTitle("JComboBox");

        this.setSize(500,500);

        this.setVisible(true);

       

   }

  

   public void actionPerformed(ActionEvent e)

   {

        if (e.getSource() == cb)

        {

             System.out.println(cb.getSelectedItem());

        }

   }

    

   public static void main(String[] args)

   {

        MyGUI sg = new MyGUI();

   }

}