本章我们介绍下拉框的使用。
创建下拉框
ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList(
"First", "Second", "Third")
);
使用ChoiceBox的构造方法来创建一个下拉框,这个构造函数接受一个obervableList。我们也可以是用setItems方法来达到这一目的,如下:
ChoiceBox cb = new ChoiceBox();
cb.setItems(FXCollections.observableArrayList(
"New Document", "Open ",
new Separator(), "Save", "Save as")
);
需要指出的是,下拉框不仅仅只能包含文本,也可以包含Separator控件,用来分割选项。如下图所示:
为下拉框设置行为
package com.chu.button;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class ChoiceBoxTest extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
FlowPane fp = new FlowPane();
ChoiceBox<Object> cb = new ChoiceBox<>();
cb.setItems(FXCollections.observableArrayList(
"English", "Open ",
new Separator(), "Save", "Save as")
);
final String [] greeting = {"aaa","bbb","ccc","ddd","eee",};
final Label label = new Label();
cb.getSelectionModel().selectedIndexProperty().addListener((ov,oldv,newv)->{
label.setText(greeting[newv.intValue()]);
});
cb.setTooltip(new Tooltip("Select the language"));
fp.getChildren().add(cb);
fp.getChildren().add(label);
Scene scene = new Scene(fp,500,300);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
设置提示
cb.setTooltip(new Tooltip("Select the language"));