Swing Examples - Using comboboxes



Following example showcase how to use standard comboboxes in a Java Swing application.

We are using the following APIs.

  • JComboBox − To create a standard combobox.

  • JCheckBox.setSelectedIndex(index); − To select an item.

  • JCheckBox.getSelectedItem(); − To get a selected item.

Example

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

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       

      String[] numbers = {"One", "Two", "Three", "Four", "Five"};
      JComboBox<String> comboBox = new JComboBox<>(numbers);
      comboBox.setSelectedIndex(3);
      comboBox.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            JComboBox combo = (JComboBox)e.getSource();
            JOptionPane.showMessageDialog(frame,combo.getSelectedItem());
        
         }
      });
      panel.add(comboBox);   
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }
}

Output

Using ComboBoxes
swingexamples_comboboxes.htm
Advertisements