Swing 示例 - 使用组合框
以下示例展示了如何在 Java Swing 应用程序中使用标准组合框。
我们使用以下 API。
JComboBox − 创建标准组合框。
JCheckBox.setSelectedIndex(index); − 选择一个项目。
JCheckBox.getSelectedItem(); − 获取选定的项目。
示例
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
String[] numbers = {"One", "Two", "Three", "Four", "Five"};
JComboBox<String> comboBox = new JComboBox<>(numbers);
comboBox.setSelectedIndex(3);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox combo = (JComboBox)e.getSource();
JOptionPane.showMessageDialog(frame,combo.getSelectedItem());
}
});
panel.add(comboBox);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
输出

swingexamples_comboboxes.html