JavaFX ListView - CRUD - ADD UPDATE DELEtE

| Page Views: 353

JavaFX ListView CRUD Tutorial and Example

This is a JavaFX ListView CRUD tutorial. We see how to perform basic CRUD - ADD UPDATE DELETE in Java FX against a ListView.

Video Tutorial(ProgrammingWizards TV Channel)

Well we have a video tutorial as an alternative to this. If you prefer tutorials like this one then it would be good you subscribe to our YouTube channel. Basically we have a TV for programming where do daily tutorials especially android.

MrListViewCRUD.java

This is our only java file. We'll make it derive from the javafx.application.Application to turn our class into a JavaFX application. That will then force us to override the start() method. It is this method that is the entry point to our JavaFX application. It will receive a Stage object as a parameter.

Our data object is a static class we call SpiritualTeacher. It will represent a single spiritual teacher and it's properties. In this case we use only a single property, that is the name. We will represent using a SimpleStringProperty object. So we will be performing CRUD operations on the SpiritualTeacher objects, adding them to our listview, updating them, showing them and deleting them.

We will be using an observableArrayList as our data source.

Here's the code:

package mrlistviewcrud;

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.control.TextField;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class MrListViewCRUD extends Application {
    /*
    Our data Object
    */
    public static class SpiritualTeacher {

        private final SimpleStringProperty name;

        private SpiritualTeacher(String name) {
            this.name = new SimpleStringProperty(name);
        }
        public String getName() {
            return name.get();
        }
        public void setName(String mName) {
            name.set(mName);
        }
        @Override
        public String toString() {
            return getName(); 
        }
    }
    /*
    ObservableList. Our data source.
    */
    private final ObservableList<SpiritualTeacher> spiritualTeachers =
            FXCollections.observableArrayList(
                    new SpiritualTeacher("Sedata"),
                    new SpiritualTeacher("Meister Eckhart"),
                    new SpiritualTeacher("Confucius"),
                    new SpiritualTeacher("Rumi"),
                    new SpiritualTeacher("Ramana Maharshi"));
    private int selectedIndex=-1;
    /*
    JavaFx Start Method
    */
    @Override
    public void start(Stage stage) throws Exception {
        Scene scene = new Scene(new Group());
        stage.setTitle("JavaFX ListView CRUD - ADD UPDATE DELETE CLEAR");
        stage.setWidth(450);
        stage.setHeight(550);

        Label nameLabel = new Label("Spiritial Teachers");
        nameLabel.setFont(new Font("Arial", 20));

        TextField nameTxt = new TextField();
        nameTxt.setPromptText("Name");

        ListView myListView=new ListView();
        myListView.setItems(spiritualTeachers);

        myListView.setOnMouseClicked(event -> {
            String selectedItem = myListView.getSelectionModel().getSelectedItem().toString();
            selectedIndex=myListView.getSelectionModel().getSelectedIndex();
            nameTxt.setText(selectedItem);
        });

        Button addButton = new Button("Add");
        addButton.setOnAction((ActionEvent e) -> {
            spiritualTeachers.add(new SpiritualTeacher(nameTxt.getText()));
            nameTxt.clear();
        });
        Button updateBtn = new Button("Update");
        updateBtn.setOnAction((ActionEvent e) -> {
            Dialog d=new Alert(Alert.AlertType.INFORMATION,String.valueOf(selectedIndex));
            d.show();
            spiritualTeachers.remove(selectedIndex);
            spiritualTeachers.add(selectedIndex, new SpiritualTeacher(nameTxt.getText()));
            nameTxt.clear();
        });
        Button deleteBtn = new Button("Delete");
        deleteBtn.setOnAction((ActionEvent e) -> {
            spiritualTeachers.remove(selectedIndex);
            nameTxt.clear();
        });
        Button clearBtn = new Button("Clear");
        clearBtn.setOnAction((ActionEvent e) -> {
            spiritualTeachers.clear();
            nameTxt.clear();
        });

        HBox myHBox = new HBox();
        myHBox.getChildren().addAll(nameTxt, addButton,updateBtn,deleteBtn,clearBtn);
        myHBox.setSpacing(3);

        VBox myVBox = new VBox();
        myVBox.setSpacing(5);
        myVBox.setPadding(new Insets(10, 0, 0, 10));
        myVBox.getChildren().addAll(nameLabel, myListView, myHBox);

        ((Group) scene.getRoot()).getChildren().addAll(myVBox);

        stage.setScene(scene);
        stage.show();
    }
    /*
    Main method
    */
    public static void main(String[] args) {
        Application.launch(args);
    }
}

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.




Recommendations


What do You Think


Previous Post Next Post