This is a Java Program to Create a Combo Box to Select One Option and Display the Label of Option Selected
We have to write a program in Java such that it creates a Combo Box containing name of some countries, and the option selected by user is displayed in the frame.
For displaying label of option selected from a Combo Box, we can have the following set of input and output.
To display the label:
When any option on the Combo Box is selected by the user, it is expected that the label of the item selected is displayed.
1. Create a combo box using the JComboBox class.
2. Add the list of countries to it.
3. Associate ItemListener with the combo box.
4. When any item is selected, display the label of item in the frame.
Here is source code of the Java Program to view the label of item selected from a Combo Box. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.
/* Java Program to view label of item selected from a Combo Box*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Combo_Box implements ItemListener
{
static JLabel text;
static JComboBox<String> box;
//Driver function
public static void main(String args[])
{
//Create a frame
JFrame frame = new JFrame("Combo Box");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
//Create an object
Combo_Box obj = new Combo_Box();
//Create a label
text = new JLabel("Select an Item");
text.setBounds(175,50,200,50);
frame.add(text);
//Create an array with countries name
String countries[]={"India","Japan","Nepal","China","Sri Lanka"};
//Create a Combo Box
box = new JComboBox<String>(countries);
box.setBounds(200,200,100,50);
box.addItemListener(obj);
frame.add(box);
//Display the frame
frame.setVisible(true);
}
//Function to view the label of item selected
public void itemStateChanged(ItemEvent e)
{
text.setText("Item Selected : "+box.getSelectedItem());
}
}
1. Create a Combo Box using JComboBox, with String data type.
2. To know which item was selected, using getSelectedItem.
Here’s the run time test cases for viewing the label of item selected from a combo box.
Test case 1 – To view the label of item selected.
Test case 2 – To view the label of item selected.
Test case 3 – To view the label of item selected.
Sanfoundry Global Education & Learning Series – Java Programs.
- Practice BCA MCQs
- Apply for Computer Science Internship
- Check Programming Books
- Check Java Books
- Practice Programming MCQs