📜  Java Swing-JComboBox

📅  最后修改于: 2020-09-30 06:00:15             🧑  作者: Mango

Java JComboBox

Choice类的对象用于显示选项的弹出菜单。用户选择的选项显示在菜单顶部。它继承了JComponent类。

JComboBox类声明

我们来看一下javax.swing.JComboBox类的声明。

public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionListener, Accessible

常用的构造函数:

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.

常用方法:

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示例

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();       
}  
} 

输出:

带有ActionListener的Java JComboBox示例

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();       
}  
}  

输出: