下面的範例展示了如何在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使用下拉式方塊(tw511.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 = {"Tw511.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);
}
}
執行上面範例程式碼,得到以下結果: