JComboBox is a swing component which allows us to display a list of options in a drop-down style. Here is an example of using JComboBox.This will help you to understand the functions associated with the combo box and event handling with it.
Output:
Source Code:
import java.awt.Component;
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.event.*;
public class ComboDemo {
public static void main(String[] args) {
ComboBox combo = new ComboBox();
}
}
class ComboBox extends JFrame implements ActionListener{
JComboBox combo;
JLabel lblSelected;
JLabel lblCombo;
final String[] comboList = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
public ComboBox(){
//set title of frame
super("Example of JComboBox");
//set layout for the frame;
setLayout(new FlowLayout());
//set size of the frame;
setSize(400,200);
//set window closing option
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//set visibility of frame;
setVisible(true);
//create label and set title/text
lblCombo = new JLabel("Select Day: ");
lblCombo.setVisible(true);
//create lable
lblSelected = new JLabel();
lblSelected.setVisible(false);
//create combo box;
combo = new JComboBox();
//set option for combo box;
combo.setModel(new DefaultComboBoxModel(comboList));
//add actionlistener
combo.addActionListener(this);
combo.setVisible(true);
//add component to frame;
add(lblCombo);
add(combo);
add(lblSelected);
}
@Override
public void actionPerformed(ActionEvent e) {
//return object and explicitly converted into JComboBox;
JComboBox combo = (JComboBox) e.getSource();
//return selected item as object and convert to string
String day = combo.getSelectedItem().toString();
//set text to the label;
lblSelected.setText("Slected: " +day);
lblSelected.setVisible(true);
}
}
Output:
No comments:
Post a Comment