Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top of a menu. It inherits JComponent class.
JComboBox class declaration
Let's see the declaration for javax.swing.JComboBox class.
- public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionListener, Accessible
Commonly used Constructors:
Constructor | Description |
---|
JComboBox() | Creates a JComboBox with a default data model. |
JComboBox(Object[] items) | Creates a JComboBox that contains the elements in the specified array. |
JComboBox(Vector<?> items) | Creates a JComboBox that contains the elements in the specified Vector. |
Commonly used Methods:
Methods | Description |
---|
void addItem(Object anObject) | It is used to add an item to the item list. |
void removeItem(Object anObject) | It is used to delete an item to the item list. |
void removeAllItems() | It is used to remove all the items from the list. |
void setEditable(boolean b) | It is used to determine whether the JComboBox is editable. |
void addActionListener(ActionListener a) | It is used to add the ActionListener. |
void addItemListener(ItemListener i) | It is used to add the ItemListener. |
Java JComboBox Example
- import javax.swing.*;
- public class ComboBoxExample {
- JFrame f;
- ComboBoxExample(){
- f=new JFrame("ComboBox Example");
- String country[]={"India","Aus","U.S.A","England","Newzealand"};
- JComboBox cb=new JComboBox(country);
- cb.setBounds(50, 50,90,20);
- f.add(cb);
- f.setLayout(null);
- f.setSize(400,500);
- f.setVisible(true);
- }
- public static void main(String[] args) {
- new ComboBoxExample();
- }
- }
Output:
Java JComboBox Example with ActionListener
- import javax.swing.*;
- import java.awt.event.*;
- public class ComboBoxExample {
- JFrame f;
- ComboBoxExample(){
- f=new JFrame("ComboBox Example");
- final JLabel label = new JLabel();
- label.setHorizontalAlignment(JLabel.CENTER);
- label.setSize(400,100);
- JButton b=new JButton("Show");
- b.setBounds(200,100,75,20);
- String languages[]={"C","C++","C#","Java","PHP"};
- final JComboBox cb=new JComboBox(languages);
- cb.setBounds(50, 100,90,20);
- f.add(cb); f.add(label); f.add(b);
- f.setLayout(null);
- f.setSize(350,350);
- f.setVisible(true);
- b.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- String data = "Programming language Selected: "
- + cb.getItemAt(cb.getSelectedIndex());
- label.setText(data);
- }
- });
- }
- public static void main(String[] args) {
- new ComboBoxExample();
- }
- }
Output:
0 comments:
Post a Comment