JavaFX ListView Demo
/**
* ListView Demo
* @author Notus(hehe_xiao@qq.com)
* @date 2017-11-14
*/
package com.test;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.MultipleSelectionModel;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class ListViewDemo extends Application {
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
// 创建根节点
FlowPane rootNode = new FlowPane(Orientation.VERTICAL, 10, 10);
rootNode.setAlignment(Pos.CENTER);
// 创建场景
Scene myScene = new Scene(rootNode, 300, 200);
// 设置舞台
primaryStage.setScene(myScene);
primaryStage.setTitle("ListView 测试");
// 创建控件
Label response = new Label("请选择电脑类型");
// 创建 ListView
ObservableList<String> computerTypes = FXCollections.observableArrayList("Smartphone", "Tablet", "Notebook", "Desktop");
ListView<String> lvComputers = new ListView<>(computerTypes);
lvComputers.setPrefSize(100, 70);
// ListView 事件处理
MultipleSelectionModel<String> lvSelModel = lvComputers.getSelectionModel();
lvSelModel.selectedItemProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
response.setText("Computer selected is " + newValue);
}
});
// 添加控件到根结点
rootNode.getChildren().addAll(lvComputers, response);
// 显示舞台
primaryStage.show();
}
}