在Java中實現下拉框有多種方式,以下是其中兩種常用方法:
使用Swing庫的JComboBox類:
import javax.swing.*;
public class ComboBoxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("ComboBox Example");
String[] items = {"Item 1", "Item 2", "Item 3"};
JComboBox<String> comboBox = new JComboBox<>(items);
comboBox.setBounds(50, 50, 90, 20);
frame.add(comboBox);
frame.setSize(200, 150);
frame.setLayout(null);
frame.setVisible(true);
}
}
使用JavaFX庫的ComboBox類:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ComboBoxExample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("ComboBox Example");
ComboBox<String> comboBox = new ComboBox<>();
ObservableList<String> items = FXCollections.observableArrayList("Item 1", "Item 2", "Item 3");
comboBox.setItems(items);
VBox vbox = new VBox(comboBox);
Scene scene = new Scene(vbox, 200, 150);
primaryStage.setScene(scene);
primaryStage.show();
}
}
以上兩種方法都可以創建一個下拉框,并將選項列表添加到下拉框中。