ObservableList in JavaFX
Fri, Dec 15, 2023
2-minute read
Here is example JavaFX application that demonstrates the use of an ObservableList
. This application will include a simple user interface where items can be added to or removed from the list, and the changes will be reflected in real-time on the UI.
Here’s a basic outline of the application:
- Main Application Class: This class extends
Application
and sets up the primary stage. - UI Elements: Includes a
ListView
to display theObservableList
, and buttons to add or remove items. - ObservableList: A list that automatically updates the
ListView
when items are added or removed.
Example JavaFX Application with ObservableList
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ObservableListExample extends Application {
private ObservableList<String> items;
@Override
public void start(Stage primaryStage) {
// Initialize the ObservableList
items = FXCollections.observableArrayList();
// Create a ListView to display the items
ListView<String> listView = new ListView<>(items);
// Buttons to add and remove items
Button addButton = new Button("Add Item");
Button removeButton = new Button("Remove Selected Item");
// Event Handler for addButton
addButton.setOnAction(e -> items.add("New Item " + (items.size() + 1)));
// Event Handler for removeButton
removeButton.setOnAction(e -> {
int selectedIndex = listView.getSelectionModel().getSelectedIndex();
if (selectedIndex != -1) {
items.remove(selectedIndex);
}
});
// Layout
VBox layout = new VBox(10, listView, addButton, removeButton);
layout.setPadding(new javafx.geometry.Insets(10));
// Set the scene and stage
Scene scene = new Scene(layout, 300, 250);
primaryStage.setTitle("ObservableList Example");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
How to Run:
- Create a JavaFX Project: Set up a JavaFX project in your IDE.
- Add the Code: Copy the above code into a new class file.
- Run the Application: Compile and run the application.
Explanation:
- The
ObservableList
is linked to theListView
. Any changes to the list (additions or removals) will automatically update theListView
. - The
addButton
adds a new item to the list. - The
removeButton
removes the selected item from the list.
This example is a simple demonstration of how an ObservableList
works in JavaFX. You can expand on this by adding more complex data types and additional UI elements.