下面的示例展示了如何在Java Swing应用程序中使用标准组合框。
使用以下API -
JComboBox
- 创建标准组合框。JCheckBox.setSelectedIndex(index);
- 选择项目。JCheckBox.getSelectedItem();
- 获取所选项目。
示例
package com.yiibai.swingdemo;
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使用组合框(yiibai.com)");
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[] sites = {"Yiibai.com", "kaops.com", "Viibm.com", "google.com", "Baidu.com"};
JComboBox<String> comboBox = new JComboBox<>(sites);
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);
}
}
执行上面示例代码,得到以下结果: