package fx;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import java.util.ArrayList;
public class Exercise16_16 extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
ComboBox<String> selectMode = new ComboBox<>(FXCollections.observableArrayList("SINGLE", "MULTIPLE")); //选择模式复选框
selectMode.setValue("SINGLE"); //选择模式设置初值
HBox topHBox = new HBox(10, new Label("Choose Selection Mode:"), selectMode);
topHBox.setAlignment(Pos.CENTER);
ListView<String> listView = new ListView<>(); //列表视图
listView.getItems().addAll("China", "Japan", "Korea", "India", "Malaysia", "Vietnam"); //列表视图添加值
listView.setPrefHeight(120); //列表视图设置高度
Text text = new Text(); //文本
selectMode.setOnAction(event -> { //选择模式注册动作事件
ObservableList<String> list = selectMode.getItems(); //获取列表
//设置选择模式
listView.getSelectionModel().setSelectionMode(list.get(list.indexOf(selectMode.getValue()
)).equals("MULTIPLE") ? SelectionMode.MULTIPLE : SelectionMode.SINGLE);
});
listView.getSelectionModel().selectedItemProperty().addListener(observable -> { //列表视图添加监听器
ObservableList<String> list = listView.getSelectionModel().getSelectedItems();
String string;
if (list.size() > 1) string = "Selected items are"; //列表大小大于1时,设置为复数
else string = "Selected item is";
for (String s : list) //添加字符串
string += (" " + s);
text.setText(string); //设置字符串
});
BorderPane pane = new BorderPane(new ScrollPane(listView));
pane.setBottom(text);
pane.setTop(topHBox);
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.setTitle("Exercise16_16");
primaryStage.show();
}
}