Java FX example of a TO DO list

Simple Java FX application which creates and removes elements from the list. This is a basic example of a To Do List application using JavaFX. The program creates a window with a text field for inputting new tasks, a list view for displaying the tasks, and two buttons for adding and removing tasks. The tasks are stored in an observable list, which allows the list view to automatically update when tasks are added or removed. The tasks are only in memory and they do not in the hard disk.

Maven pom.xml file with JavaFX dependencies:

     <!-- other dependencies -->

Java code:

package com.example.testjavafx;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TodoList extends Application {

    private TextField taskInput;
    private ListView<String> taskList;
    private ObservableList<String> tasks;

    public static void main(String[] args) {

    public void start(Stage primaryStage) {
        primaryStage.setTitle("Todo List");

        taskInput = new TextField();
        taskInput.setPromptText("Enter a new task");

        Button addButton = new Button("Add");
        addButton.setOnAction(e -> addTask());
        // make Add button default.
        // This way if we press Enter then it will be activated

        Button removeButton = new Button("Remove");
        removeButton.setOnAction(e -> removeTask());

        tasks = FXCollections.observableArrayList();
        taskList = new ListView<>(tasks);

        HBox buttonLayout = new HBox();
        buttonLayout.getChildren().addAll(taskInput, addButton, removeButton);

        VBox layout = new VBox();
        layout.setPadding(new Insets(10, 10, 10, 10));
        layout.getChildren().addAll(buttonLayout, taskList);

        Scene scene = new Scene(layout, 400, 300);

    private void addTask() {
        String task = taskInput.getText();
        if (!task.isEmpty()) {

    private void removeTask() {
        int selectedIndex = taskList.getSelectionModel().getSelectedIndex();
        if (selectedIndex != -1) {

The result is:

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.