Showing a table in javaFX desktop application

Showing a table in javaFX desktop application – in just few steps

In this tutorial you will learn how to show a table in your javaFX application.

We assume that you have basic JAVA knowledge and that you already created your main window.

First of all we need to create a model that will fill our table. Let’s imagine that we are creating a hotel room management application, so we will need the room’s model(class)

Here is how to create it:

Room.java

[code language=”java”]
// Showing a table in javaFX desktop application
import javafx.beans.property.SimpleStringProperty;

public class Room {

private SimpleStringProperty id;
private SimpleStringProperty description;
private SimpleStringProperty isForRepair;
private SimpleStringProperty comment;
private SimpleStringProperty internalId;

public Room(String id, String description, String isForRepair, String comment, String internalId) {
this.id = new SimpleStringProperty(id);
this.description = new SimpleStringProperty(description);
this.isForRepair = new SimpleStringProperty(isForRepair);
this.comment = new SimpleStringProperty(comment);
this.internalId = new SimpleStringProperty(internalId);
}

public String getId() {
return id.get();
}

public void setId(String ID) {
id.set(ID);
}

public String getDescription() {
return description.get();
}

public void setDescription(String desc) {
description.set(desc);
}

public String getIsForRepair() {
return isForRepair.get();
}

public void setIsForRepair(String isFor) {
isForRepair.set(isFor);
}

public String getComment() {
return comment.get();
}

public void setComment(String comments) {
comment.set(comments);
}

public String getInternalId() {
return internalId.get();
}

public void setInternalId(String internal) {
internalId.set(internal);
}

}
// Showing a table in javaFX desktop application
[/code]

The above class will represent a single row of our table. As you can see the room have few properties as id, description, a repair status and so on – you can add your own methods and properties to the Room’s class – this is just an example of the structure that you will need for your project.

Now let’s move to the main screen – the one that contains the table with all the properties:

Rooms.java

[code language=”java”]
package com.ereception.screens;

import com.ereception.db.Queries;
import com.ereception.models.Room;
import com.ereception.tools.Logger;
import com.ereception.tools.Tools;
import java.sql.SQLException;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
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;
import org.json.JSONArray;
import org.json.JSONException;

//Showing a table in javaFX desktop application
public class RoomsManager {

final Logger logger = new Logger();
final Tools tools = new Tools();

private final TableView<Room> table = new TableView<>();
private final ObservableList<Room> data = FXCollections.observableArrayList();
final HBox hb = new HBox();

final Queries query = new Queries();

public void start() {

Stage stage = new Stage();

Scene scene = new Scene(new Group());
stage.setTitle("Rooms manager");
stage.setWidth(630);
stage.setHeight(550);

final Label label = new Label("Rooms");
label.setFont(new Font("Arial", 20));

table.setEditable(true);

TableColumn roomRemoveCol = new TableColumn("Remove");
roomRemoveCol.setMinWidth(100);
roomRemoveCol.setCellValueFactory(new PropertyValueFactory<>("id"));
roomRemoveCol.setCellFactory(TextFieldTableCell.forTableColumn());

TableColumn roomIdCol = new TableColumn("Room ID");
roomIdCol.setMinWidth(100);
roomIdCol.setCellValueFactory(
new PropertyValueFactory<>("id"));
roomIdCol.setCellFactory(TextFieldTableCell.forTableColumn());
roomIdCol.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Room, String>>() {
@Override
public void handle(TableColumn.CellEditEvent<Room, String> t) {
boolean isUpdated = query.updateRoomId(((Room) t.getTableView().getItems().get(t.getTablePosition().getRow())).getInternalId(), t.getNewValue());
if (isUpdated) {
((Room) t.getTableView().getItems().get(t.getTablePosition().getRow())).setId(t.getNewValue());
} else {
tools.alert("Something got wrong! The change is NOT saved!");
}
}
}
);

TableColumn roomDescriptionCol = new TableColumn("Room description");
roomDescriptionCol.setMinWidth(100);
roomDescriptionCol.setCellValueFactory(
new PropertyValueFactory<>("description"));
roomDescriptionCol.setCellFactory(TextFieldTableCell.forTableColumn());
roomDescriptionCol.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Room, String>>() {
@Override
public void handle(TableColumn.CellEditEvent<Room, String> t) {
boolean isUpdated = query.updateRoomDescription(((Room) t.getTableView().getItems().get(t.getTablePosition().getRow())).getInternalId(), t.getNewValue());
if (isUpdated) {
((Room) t.getTableView().getItems().get(t.getTablePosition().getRow())).setDescription(t.getNewValue());
} else {
tools.alert("Something got wrong! The change is NOT saved!");
}
}
}
);

TableColumn isForRepairtCol = new TableColumn("Needs repair");
isForRepairtCol.setMinWidth(200);
isForRepairtCol.setCellValueFactory(
new PropertyValueFactory<>("isForRepair"));
isForRepairtCol.setCellFactory(TextFieldTableCell.forTableColumn());
isForRepairtCol.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Room, String>>() {
@Override
public void handle(TableColumn.CellEditEvent<Room, String> t) {
boolean isUpdated = query.updateRoomRepair(((Room) t.getTableView().getItems().get(t.getTablePosition().getRow())).getInternalId(), t.getNewValue());
if (isUpdated) {
((Room) t.getTableView().getItems().get(t.getTablePosition().getRow())).setIsForRepair(t.getNewValue());
} else {
tools.alert("Something got wrong! The change is NOT saved!");
}
}
}
);

TableColumn commentCol = new TableColumn("Comment");
commentCol.setMinWidth(200);
commentCol.setCellValueFactory(
new PropertyValueFactory<>("comment"));
commentCol.setCellFactory(TextFieldTableCell.forTableColumn());
commentCol.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Room, String>>() {
@Override
public void handle(TableColumn.CellEditEvent<Room, String> t) {
boolean isUpdated = query.updateRoomComment(((Room) t.getTableView().getItems().get(t.getTablePosition().getRow())).getInternalId(), t.getNewValue());
if (isUpdated) {
((Room) t.getTableView().getItems().get(t.getTablePosition().getRow())).setComment(t.getNewValue());
} else {
tools.alert("Something got wrong! The change is NOT saved!");
}
}
}
);

table.setItems(data);
table.getColumns().addAll(roomIdCol, roomDescriptionCol, isForRepairtCol, commentCol, roomRemoveCol);

final TextField txtRoomId = new TextField();
txtRoomId.setPromptText("Room ID");
txtRoomId.setMaxWidth(roomIdCol.getPrefWidth());

final TextField txtRoomDescription = new TextField();
txtRoomDescription.setMaxWidth(roomDescriptionCol.getPrefWidth());
txtRoomDescription.setPromptText("Description");

final TextField txtIsForRepair = new TextField();
txtIsForRepair.setMaxWidth(isForRepairtCol.getPrefWidth());
txtIsForRepair.setPromptText("Needs repair");

final TextField txtComment = new TextField();
txtComment.setMaxWidth(commentCol.getPrefWidth());
txtComment.setPromptText("Comment");

final Button addButton = new Button("Add");
addButton.setOnAction((ActionEvent e) -> {
boolean isInserted = query.insertRoom(txtRoomId.getText(), txtRoomDescription.getText(), txtIsForRepair.getText(), txtComment.getText());
if (isInserted) {
try {
data.add(new Room(
txtRoomId.getText(),
txtRoomDescription.getText(),
txtIsForRepair.getText(),
txtComment.getText(),
query.getMaxRoomId()));
} catch (SQLException ex) {
logger.log(ex.toString());
}
txtRoomId.clear();
txtRoomDescription.clear();
txtIsForRepair.clear();
txtComment.clear();
}
});

hb.getChildren().addAll(txtRoomId, txtRoomDescription, txtIsForRepair, txtComment, addButton);
hb.setSpacing(3);

final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label, table, hb);

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

stage.setScene(scene);
// stage.setResizable(false);

new Thread() {
@Override
public void run() {
try {
JSONArray rooms = query.getRooms();

for (int i = 0; i < rooms.length(); i++) {
data.add(new Room(
rooms.getJSONObject(i).getString("roomId"),
rooms.getJSONObject(i).getString("description"),
rooms.getJSONObject(i).getString("isForRepair"),
rooms.getJSONObject(i).getString("comment"),
rooms.getJSONObject(i).getString("id")));
}
} catch (SQLException | JSONException e) {
logger.log(e.toString());
}
}
}.start();

stage.show();
}
}

// Showing a table in javaFX desktop application
[/code]

Let’s explain what is happening in the above code.

You are creating a basic windows containing the table inside of it. The window also contains 2 text fields and an add button.
The function names are made just for example – you will need to create your own methods that are fitting your model needs.

If you follow the code step by step you will understand the basic concept and the structure as the add button is containing the which should be inside of your methods.

One of the most important parts is

[code language=”java”]
getChildren().addAll(txtRoomId, txtRoomDescription, txtIsForRepair, txtComment, addButton);
[/code]

As this is applying the changes to your table and refreshing the view.

If you followed the Showing the table in javaFX desktop application tutorial your window should be looking like the picture below

rsz_screenshot_from_2015-09-18_154359



Leave a Reply