Friday, June 3, 2016

23. ListView

A ListView object is created with a list of colors.


The selected color is written in the show label, at the bottom, when the 'Select' button is pressed.


package ex23;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Ex23 extends Application {
    
    ListView listView;
    Label show;
    
    @Override
    public void start(Stage primaryStage) {
        
        VBox root = new VBox(10);
        Label label = new Label("Colors");
        listView = new ListView<>();
        listView.getItems().addAll("Red", "Green", "Blue", "Yellow");
        listView.getSelectionModel().selectLast();
        Button button = new Button("Select");
        show = new Label("Press Select");
        button.setOnAction(e -> sel());
        root.getChildren().addAll(label, listView, button, show);
        root.setPadding(new Insets(20));
    
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setTitle("Example 23. ListView");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    private void sel() {
        show.setText("Selected color is " +
                     listView.getSelectionModel().getSelectedItem());
    }
}

This is the output:


No comments:

Post a Comment