package javafxsamples; import javafx.application.Application; import javafx.beans.binding.Bindings; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.builders.ButtonBuilder; import javafx.builders.HBoxBuilder; import javafx.builders.VBoxBuilder; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * Test for listView selection * @author Alex */ public class ListViewTest extends Application{ @Override public void start(Stage primaryStage) throws Exception { final ListView listView = new ListView(); listView.getItems().add("test"); listView.getSelectionModel().select(0); final Label labelIndex = new Label(); final Label labelObj = new Label(); listView.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener(){ @Override public void changed(ObservableValue observable, Number oldValue, Number newValue) { System.out.println("selected index: oldvalue="+oldValue +", newValue="+newValue); labelIndex.setText(newValue.toString()); labelObj.setText(listView.getSelectionModel().selectedItemProperty().toString()); } }); // labelIndex.textProperty().bind( // Bindings.concat(listView.getSelectionModel().selectedIndexProperty())); // labelObj.textProperty().bind( // Bindings.concat(listView.getSelectionModel().selectedItemProperty())); final Button button = new ButtonBuilder() .text("modify") .onAction(new EventHandler() { @Override public void handle(ActionEvent event) { listView.getItems().clear(); listView.getItems().add("test1"); listView.getItems().add("test2"); } }).build(); VBox box = new VBoxBuilder() .children( button, new HBoxBuilder().children(new Label("index:"), labelIndex).build(), new HBoxBuilder().children(new Label("selection:"), labelObj).build(), listView) .build(); primaryStage.setScene(new Scene(box, 200, 100)); primaryStage.setVisible(true); } public static void main(String[] args) { launch(args); } }