Home Tutorial Java Swing Java swing: get selected value from combobox

 
 

Share on Google+Share on Google+
Java swing: get selected value from combobox
Posted on: September 25, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to get selected value from combobox.

Java swing: get selected value from combobox

In this tutorial, you will learn how to get selected value from combobox.

The combobox provides the list of option and let the user to choose one from  several choices. Only one option is selected at a time. In the given example, we have added the list of programming languages to the combobox using addItem() of JComboBox class. We have imposed an actionlistener on the combobox in order to get the selected value from combobox. The Itemselectable interface allow to select an option from the combobox. The method selectedString() returns the selected string.

Example:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class  ComboExample{

    public static void main(String[] args) throws Exception{
        JFrame f=new JFrame();
        f.setLayout(null);
        JLabel lab=new JLabel("Select Programming Language: ");
        final JComboBox combo=new JComboBox();
        combo.addItem("--Select--");
           combo.addItem("Java");
		   combo.addItem("C/C++");
		   combo.addItem(".NET");
		   combo.addItem("Perl");
           

        ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
        ItemSelectable is = (ItemSelectable)actionEvent.getSource();
        String name=selectedString(is);
        JOptionPane.showMessageDialog(null,"You have Selected: " + name);
        }
    };
       combo.addActionListener(actionListener);
        lab.setBounds(20,20,200,20);
        combo.setBounds(200,20,80,20);
        f.add(lab);
        f.add(combo);

        f.setVisible(true);
        f.setSize(300,120);
    }
    static private String selectedString(ItemSelectable is) {
    Object selected[] = is.getSelectedObjects();
    return ((selected.length == 0) ? "null" : (String)selected[0]);
  } 
}


Output:

Advertisement

Related Tags for Java swing: get selected value from combobox:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 25, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com