javafx listview

w‮igi.ww‬ftidea.com

In JavaFX, a ListView is a control that displays a scrollable list of items. It is often used to display a list of objects and allows users to select one or more items from the list.

Here's an example of how to create and use a ListView in a JavaFX application:

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class MyJavaFXApp extends Application {

    @Override
    public void start(Stage primaryStage) {
        // Create a list of items for the ListView
        ObservableList<String> items = FXCollections.observableArrayList(
            "Item 1", "Item 2", "Item 3", "Item 4", "Item 5"
        );
        
        // Create a new ListView and set the items
        ListView<String> listView = new ListView<>(items);
        listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        
        // Add the ListView to a VBox layout
        VBox layout = new VBox(listView);
        
        // Create a Scene object with the layout and set it on the stage
        Scene scene = new Scene(layout, 300, 200);
        primaryStage.setScene(scene);

        // Show the stage
        primaryStage.show();
    }

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

In this example, we create a ListView with a list of five items. We set the selection mode of the ListView to SelectionMode.MULTIPLE, which allows users to select multiple items from the list. We then add the ListView to a VBox layout and set the VBox as the root of the Scene. Finally, we display the scene on the stage using the show() method.

The ListView class provides a number of methods for configuring the appearance and behavior of the control. You can set the list of items using the setItems() method, set the selection mode using the getSelectionModel() method, and get the selected items using the getSelectionModel().getSelectedItems() method. You can also use the setCellFactory() method to customize the appearance of each cell in the list.