Swing JComboBox Class



Swing JComboBox Class :

package com.c4learn.swing;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class JComboBoxDemo {

  private JFrame mainFrame;
  private JLabel headLabel;
  private JLabel msgLabel;
  private JPanel mainPanel;

  public JComboBoxDemo() {
    mainFrame = new JFrame("Java Swing Examples");
    mainFrame.setSize(400, 400);
    mainFrame.setLayout(new GridLayout(3, 1));

    headLabel = new JLabel("JComboBox Demo", JLabel.CENTER);
    msgLabel = new JLabel("No Selection", JLabel.CENTER);
    mainPanel = new JPanel();
    mainPanel.setLayout(new FlowLayout());

    mainFrame.add(headLabel);
    mainFrame.add(mainPanel);
    mainFrame.add(msgLabel);
    mainFrame.setVisible(true);
  }

  public static void main(String[] args) {
    JComboBoxDemo swingControlDemo = new JComboBoxDemo();
    swingControlDemo.showListDemo();
  }

  private void showListDemo() {

    final DefaultComboBoxModel langList = 
                      new DefaultComboBoxModel();
          
    langList.addElement("English");
    langList.addElement("German");
    langList.addElement("French");
    langList.addElement("Hindi");
    langList.addElement("Marathi");

    final JComboBox cLang = new JComboBox(langList);
    cLang.setSelectedIndex(0);
    JScrollPane langScrollPane = new JScrollPane(cLang);

    JButton btnDisplay = new JButton("Display");

    btnDisplay.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String str = "Selected Language : ";
        if (cLang.getSelectedIndex() != -1) {
          str += cLang.getItemAt(cLang.getSelectedIndex());
        }
        msgLabel.setText(str);
      }
    });

    mainPanel.add(langScrollPane);
    mainPanel.add(btnDisplay);
    mainFrame.setVisible(true);
  }
}

Output :

Swing JComboBox Class