Example code:
package javafxchoicebox; import javafx.application.Application; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaFXChoiceBox extends Application { @Override public void start(Stage primaryStage) { Label label1 = new Label(); Label label2 = new Label(); ChoiceBox choiceBox = new ChoiceBox( FXCollections.observableArrayList( "java-buddy", "Java", "Buddy") ); choiceBox.getSelectionModel().selectFirst(); choiceBox.getSelectionModel().selectedItemProperty() .addListener((ObservableValue observable, Object oldValue, Object newValue) -> { label1.setText((String)newValue); }); Button btn = new Button(); btn.setText("Say 'Hello World'"); btn.setOnAction((ActionEvent event) -> { String selected = choiceBox.getSelectionModel() .getSelectedItem().toString(); label2.setText("Hello " + selected); }); VBox root = new VBox(); root.getChildren().addAll(choiceBox, btn, label1, label2); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
This comment has been removed by the author.
ReplyDeleteAlso, if I remove the "...selectFirst()" line, I am able to select an item -- one time. It will not let me select anything after that.
ReplyDelete