Monday, 18 June 2018

JavaFX: Edit data in a table

This is continuation to my previous posts. I would recommend you to go through my previous post. In this post, I am going to enhance (Add edit functionality) the table application created in previous post.

Step 1: By using the ‘setEditable’ method of TableView class, you can enable the editing in a table.

Ex
TableView tableView = new TableView();
tableView.setEditable(true);

Step 2: Add event handlers to the table columns.

                  TableView<Friend> tableView = new TableView<>();
                  tableView.setEditable(true);

                  TableColumn<Friend, String> firstNameCol = new TableColumn<>("First Name");
                  firstNameCol.setMinWidth(300);

                  TableColumn<Friend, String> lastNameCol = new TableColumn<>("Last Name");
                  lastNameCol.setMinWidth(300);

                  TableColumn<Friend, String> emailCol = new TableColumn<>("Email");
                  emailCol.setMinWidth(300);

                  tableView.getColumns().addAll(firstNameCol, lastNameCol, emailCol);

                  firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));
                  lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));
                  emailCol.setCellValueFactory(new PropertyValueFactory<>("email"));

                  firstNameCol.setCellFactory(TextFieldTableCell.<Friend> forTableColumn());
                  firstNameCol.setOnEditCommit(new EventHandler<CellEditEvent<Friend, String>>() {

                           @Override
                           public void handle(CellEditEvent<Friend, String> event) {
                                    final String value = event.getNewValue() != null ? event.getNewValue() : event.getOldValue();
                                    ((Friend) event.getTableView().getItems().get(event.getTablePosition().getRow())).setFirstName(value);
                                    tableView.refresh();

                           }
                  });

                  lastNameCol.setCellFactory(TextFieldTableCell.<Friend> forTableColumn());
                  lastNameCol.setOnEditCommit(new EventHandler<CellEditEvent<Friend, String>>() {

                           @Override
                           public void handle(CellEditEvent<Friend, String> event) {
                                    final String value = event.getNewValue() != null ? event.getNewValue() : event.getOldValue();
                                    ((Friend) event.getTableView().getItems().get(event.getTablePosition().getRow())).setLastName(value);
                                    tableView.refresh();

                           }
                  });

                  emailCol.setCellFactory(TextFieldTableCell.<Friend> forTableColumn());
                  emailCol.setOnEditCommit(new EventHandler<CellEditEvent<Friend, String>>() {

                           @Override
                           public void handle(CellEditEvent<Friend, String> event) {
                                    final String value = event.getNewValue() != null ? event.getNewValue() : event.getOldValue();
                                    ((Friend) event.getTableView().getItems().get(event.getTablePosition().getRow())).setEmail(value);
                                    tableView.refresh();
                           }
                  });

                  tableView.setItems(data);

Find the below working application.

Friend.java
package com.sample.model;

public class Friend {
 private String firstName;
 private String lastName;
 private String email;

 public Friend(String fName, String lName, String email) {
  this.firstName = fName;
  this.lastName = lName;
  this.email = email;
 }

 public String getFirstName() {
  return firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public String getEmail() {
  return email;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public void setEmail(String email) {
  this.email = email;
 }

}

TableViewApp.java
package com.sample.demos;

import com.sample.model.Friend;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class TableViewApp extends Application {
 private static final ObservableList<Friend> data = FXCollections.observableArrayList(
   new Friend("Hari", "Krishna", "krishna@krishna.com"),
   new Friend("Bhairava", "beddu", "bhairava@bhairava.com"),
   new Friend("ahswani", "sharmaSekar", "ashwani@ashwani.com"),
   new Friend("chandra", "babu", "chandra@babu.com"));

 @SuppressWarnings("unchecked")
 @Override
 public void start(Stage primaryStage) {
  Label label = new Label("My Friends List");
  label.setFont(new Font("Arial", 30));

  TableView<Friend> tableView = new TableView<>();
  tableView.setEditable(true);

  TableColumn<Friend, String> firstNameCol = new TableColumn<>("First Name");
  firstNameCol.setMinWidth(300);

  TableColumn<Friend, String> lastNameCol = new TableColumn<>("Last Name");
  lastNameCol.setMinWidth(300);

  TableColumn<Friend, String> emailCol = new TableColumn<>("Email");
  emailCol.setMinWidth(300);

  tableView.getColumns().addAll(firstNameCol, lastNameCol, emailCol);

  firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));
  lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));
  emailCol.setCellValueFactory(new PropertyValueFactory<>("email"));

  firstNameCol.setCellFactory(TextFieldTableCell.<Friend> forTableColumn());
  firstNameCol.setOnEditCommit(new EventHandler<CellEditEvent<Friend, String>>() {

   @Override
   public void handle(CellEditEvent<Friend, String> event) {
    final String value = event.getNewValue() != null ? event.getNewValue() : event.getOldValue();
    ((Friend) event.getTableView().getItems().get(event.getTablePosition().getRow())).setFirstName(value);
    tableView.refresh();

   }
  });

  lastNameCol.setCellFactory(TextFieldTableCell.<Friend> forTableColumn());
  lastNameCol.setOnEditCommit(new EventHandler<CellEditEvent<Friend, String>>() {

   @Override
   public void handle(CellEditEvent<Friend, String> event) {
    final String value = event.getNewValue() != null ? event.getNewValue() : event.getOldValue();
    ((Friend) event.getTableView().getItems().get(event.getTablePosition().getRow())).setLastName(value);
    tableView.refresh();

   }
  });

  emailCol.setCellFactory(TextFieldTableCell.<Friend> forTableColumn());
  emailCol.setOnEditCommit(new EventHandler<CellEditEvent<Friend, String>>() {

   @Override
   public void handle(CellEditEvent<Friend, String> event) {
    final String value = event.getNewValue() != null ? event.getNewValue() : event.getOldValue();
    ((Friend) event.getTableView().getItems().get(event.getTablePosition().getRow())).setEmail(value);
    tableView.refresh();
   }
  });

  tableView.setItems(data);

  final TextField addFirstName = new TextField();
  addFirstName.setPromptText("First Name");
  addFirstName.setMaxWidth(firstNameCol.getPrefWidth());

  final TextField addLastName = new TextField();
  addLastName.setMaxWidth(lastNameCol.getPrefWidth());
  addLastName.setPromptText("Last Name");

  final TextField addEmail = new TextField();
  addEmail.setMaxWidth(emailCol.getPrefWidth());
  addEmail.setPromptText("Email");

  final Button addButton = new Button("Add");
  addButton.setOnAction((ActionEvent e) -> {
   data.add(new Friend(addFirstName.getText(), addLastName.getText(), addEmail.getText()));
   addFirstName.clear();
   addLastName.clear();
   addEmail.clear();
  });

  HBox hBox = new HBox(10, addFirstName, addLastName, addEmail, addButton);

  VBox vBox = new VBox(10, label, tableView, hBox);
  vBox.setSpacing(5);
  vBox.setPadding(new Insets(10, 10, 10, 10));

  primaryStage.setScene(new Scene(vBox));
  primaryStage.setTitle("Table View Example");
  primaryStage.setWidth(900);
  primaryStage.setHeight(500);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(TableViewApp.class, args);
 }
}






Previous                                                 Next                                                 Home

No comments:

Post a Comment