Quick Review On How To Create a Simple GUI in JavaFX

Quick Review On How To Create a Simple GUI in JavaFX Main Logo

Quick Review On How To Create a Simple GUI in JavaFX

Hi there!

In this article, you will find out how you can use a JavaFX by creating a simple GUI interface with some buttons. Perhaps, someone will find answers to questions that have arisen once.

The idea

To create a set of people (suppose they work in a company), each of which will know the name, age, salary and marital status. Our window, firstly, will display information about each of them, secondly, change the salary of any employee, thirdly, be able to add a new employee, and, finally, in four, will be able to filter employees according to from the values of their attributes. The result should be something like this:

Quick Review On How To Create a Simple GUI in JavaFX Main Photo 1

Let’s get started!

First of all, we create the main Company class, from where the application will start:


package company;

public class Company {

public static void main(String[] args) {

}

}

In this class, we will extend the capabilities of the Application class. From it we need mainly the start () method, in which the main action will occur (we will skip the errors that arise in this method, in other words, if something goes wrong, our window will not close, but the console will show StackTrace errors) :


package company;

import javafx.application.Application;
import javafx.stage.Stage;

public class Company extends Application {

public void start(Stage primaryStage) throws Exception {

}

public static void main(String[] args) {
launch(args);
}

}

Excellent. In order to work with representatives of the company’s employees, we create the User class: objects of this class and will act as employees.


package company;

public class User {

User(String name, int age, int salary, boolean married) {
this.name = name;
this.age = age;
this.salary = salary;
this.married = married;
}

public void changeSalary(int x) {
salary = (salary + x <= 0)? 0: salary + x;
}

public String toString() {
return name;
}

public String getAge() {
return String.valueOf(age);
}

public String getSalary() {
return String.valueOf(salary);
}
public String getMarried() {
return (married)? ("married"):("single");
}

String name;
int age;
int salary;
boolean married;
}

Create

While the application does not start, nothing happens. To appear at least a window, it must be added. We will do this.


package company;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Company extends Application {

public void start(Stage primaryStage) throws Exception {
Scene scene = new Scene(root, WIDTH, HEIGHT);
primaryStage.setTitle("Company");
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {
launch(args);
}

Group root = new Group();

final private int WIDTH = 1000;
final private int HEIGHT = 600;

}

What we just did: we added a scene (size), gave it the name “Company”. On our scene, there is a group of the root, which in its essence is a “container”, which will contain all the buttons.

Add a drop-down list with our employees. Let’s create HBox, in which we put our combo box ComboBox userBox and the button that will give out information about the employee (HBox itself will be placed in VBox):


package company;

import java.util.ArrayList;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class Company extends Application {

public void start(Stage primaryStage) throws Exception {

users.add(new User("Alice", 20, 150, false));
users.add(new User("Bob", 34, 300, true));
users.add(new User("Peter", 18, 100, false));
users.add(new User("Kate", 38, 300, true));
users.add(new User("Steve", 31, 250, true));
users.add(new User("Alan", 62, 500, true));
users.add(new User("Julia", 33, 320, true));
users.add(new User("Patric", 37, 300, true));
users.add(new User("Alexander", 34, 280, true));
users.add(new User("George", 28, 180, true));
users.add(new User("Mary", 22, 190, false));

userBox.getItems().addAll(users);

root.getChildren().add(strings);

strings.setPadding(new Insets(10, 30, 10, 30));
strings.setSpacing(20);

strings.getChildren().add(new Text("Select the user"));
strings.getChildren().add(buttonBox);

buttonBox.setSpacing(10);
buttonBox.getChildren().add(userBox);

Scene scene = new Scene(root, WIDTH, HEIGHT);
primaryStage.setTitle("Company");
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {
launch(args);
}

Group root = new Group();

VBox strings = new VBox();

HBox buttonBox = new HBox();

ComboBox<User> userBox = new ComboBox<>();

final private int WIDTH = 1000;
final private int HEIGHT = 600;

private ArrayList<User> users = new ArrayList<>();

}

Quick Review On How To Create a Simple GUI in JavaFX Main Photo 2

What is VBox, HBox, and ComboBox

HBox is a set of buttons, texts, fields for input, each object of which is arranged in series horizontally. Similar to it, VBox is the same but stores its objects (children) vertically. We will use the following scheme: we create VBox, into which we will put several HBoxes, in each of which we put a sequence of buttons and fields.

ComboBox – it’s just a drop-down list.

Now we want to create a button that will provide information about the selected employee. Add the button (Button) and the text field (TextField), in which the text will be displayed. Add these two objects to the HBox:


package company;

/* */

public class Company extends Application {

public void start(Stage primaryStage) throws Exception {

/* */

buttonBox.setSpacing(10);
buttonBox.getChildren().add(userBox);
buttonBox.getChildren().add(buttonGetInfo);
buttonBox.getChildren().add(textInfo);

/* */
}

/* */

Button buttonGetInfo = new Button("Info");
Text textInfo = new Text();

/* */

}

Quick Review On How To Create a Simple GUI in JavaFX Main Photo 3

But while this button does nothing. In order for it to do something, she must assign an action:


buttonGetInfo.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
User u = (User) userBox.getSelectionModel().getSelectedItem();
if (u != null) {
textInfo.setText("Age is " + u.getAge() + ", " +
"Salary is " + u.getSalary() + ", " +
"Relationship: " + u.getMarried());
} else {
textInfo.setText("User not selected");
}
}
});

Quick Review On How To Create a Simple GUI in JavaFX Main Photo 4

Further actions

Absolutely similarly we add two more HBoxs: in the second one, there will be a salary change, in the third – the addition of a new employee. Due to the fact that the logic here is absolutely the same, let’s skip explanations for these moments and immediately show the result:

Quick Review On How To Create a Simple GUI in JavaFX Main Photo 5


package company;

import java.util.ArrayList;

import javafx.application.Application;
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.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class Company extends Application {

public void start(Stage primaryStage) throws Exception {

users.add(new User("Alice", 20, 150, false));
users.add(new User("Bob", 34, 300, true));
users.add(new User("Peter", 18, 100, false));
users.add(new User("Kate", 38, 300, true));
users.add(new User("Steve", 31, 250, true));
users.add(new User("Alan", 62, 500, true));
users.add(new User("Julia", 33, 320, true));
users.add(new User("Patric", 37, 300, true));
users.add(new User("Alexander", 34, 280, true));
users.add(new User("George", 28, 180, true));
users.add(new User("Mary", 22, 190, false));

userBox.getItems().addAll(users);

root.getChildren().add(strings);

strings.setPadding(new Insets(10, 30, 10, 30));
strings.setSpacing(20);

strings.getChildren().add(new Text("Select the user"));
strings.getChildren().add(buttonBox);
strings.getChildren().add(new Text("Change the salary"));
strings.getChildren().add(changeSalaryBox);
strings.getChildren().add(new Text("Add new User"));
strings.getChildren().add(addUserBox);

buttonBox.setSpacing(10);
buttonBox.getChildren().add(userBox);
buttonBox.getChildren().add(buttonGetInfo);
buttonBox.getChildren().add(textInfo);

changeSalaryBox.setSpacing(10);
changeSalaryBox.getChildren().add(buttonChangeSalary);
changeSalaryBox.getChildren().add(howMuchChange);

addUserBox.setSpacing(10);
addUserBox.getChildren().add(new Text("Name: "));
addUserBox.getChildren().add(name);
addUserBox.getChildren().add(new Text("Age: "));
addUserBox.getChildren().add(age);
addUserBox.getChildren().add(new Text("Salary: "));
addUserBox.getChildren().add(salary);
addUserBox.getChildren().add(new Text("Married: "));
addUserBox.getChildren().add(married);
addUserBox.getChildren().add(buttonAddUser);

buttonGetInfo.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
User u = (User) userBox.getSelectionModel().getSelectedItem();
if (u != null) {
textInfo.setText("Age is " + u.getAge() + ", " +
"Salary is " + u.getSalary() + ", " +
"Relationship: " + u.getMarried());
} else {
textInfo.setText("User not selected");
}
}
});

buttonChangeSalary.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {

User u = (User) userBox.getSelectionModel().getSelectedItem();
if(u != null) {
u.changeSalary(Integer.parseInt(howMuchChange.getText()));
textInfo.setText("Age is " + u.getAge() + ", " +
"Salary is " + u.getSalary() + ", " +
"Relationshp: " + u.getMarried());
howMuchChange.clear();
}
}
});

buttonAddUser.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
String m = married.getText();
boolean mm = (m.equals("married"))? true:false;
User u = new User(name.getText(), Integer.parseInt(age.getText()),
Integer.parseInt(salary.getText()), mm);
users.add(u);
userBox.getItems().addAll(u);
name.clear();
age.clear();
salary.clear();
married.clear();
}
});

Scene scene = new Scene(root, WIDTH, HEIGHT);
primaryStage.setTitle("Company");
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {
launch(args);
}

Group root = new Group();

VBox strings = new VBox();

HBox buttonBox = new HBox();
ComboBox<User> userBox = new ComboBox<>();
Button buttonGetInfo = new Button("Info");
Text textInfo = new Text();

HBox changeSalaryBox = new HBox();
Button buttonChangeSalary = new Button("Change salary");
TextField howMuchChange = new TextField();

HBox addUserBox = new HBox();
Button buttonAddUser = new Button("Add User");
TextField name = new TextField();
TextField age = new TextField();
TextField salary = new TextField();
TextField married = new TextField();

final private int WIDTH = 1000;
final private int HEIGHT = 600;

private ArrayList<User> users = new ArrayList<>();

}

Filters

Now we add the “filtering” of employees by attributes. Again, the lists for filters will be added using the ComboBox for the same logic.


package company;

/* */

public class Company extends Application {

public void start(Stage primaryStage) throws Exception {

/* */

ageFilterBox.getItems().addAll(
"no matter",
"over 20",
"over 30",
"over 40"
);

salaryFilterBox.getItems().addAll(
"no matter",
"over 150",
"over 250",
"over 500"
);

relationshipFilterBox.getItems().addAll(
"no matter",
"married",
"single"
);

/* */
strings.getChildren().add(filters);
strings.getChildren().add(resultFilter);

/* */

filters.setSpacing(10);
filters.getChildren().add(new Text("Age"));
filters.getChildren().add(ageFilterBox);
filters.getChildren().add(new Text("Salary"));
filters.getChildren().add(salaryFilterBox);
filters.getChildren().add(new Text("Relationship"));
filters.getChildren().add(relationshipFilterBox);
filters.getChildren().add(filter);

/* */

filter.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
int age;
int index = ageFilterBox.getSelectionModel().getSelectedIndex();
age = (index == 0)? 0: (index == 1)? 21: (index == 2)? 31: 41;

int salary;
index = salaryFilterBox.getSelectionModel().getSelectedIndex();
salary = (index == 0)? 0 : (index == 1)? 151 : (index == 2)? 251:501;

boolean relate;
index = relationshipFilterBox.getSelectionModel().getSelectedIndex();
relate = (index == 1)? true: (index == 2)? false: true;

List<User> list;
if(index != 0) { list = users.stream().
filter(u -> u.age > age).
filter(u -> u.salary > salary).
filter(u -> u.married == relate).
collect(Collectors.toList()); }

else { list = users.stream().
filter(u -> u.age > age).
filter(u -> u.salary > salary).
collect(Collectors.toList()); }

String res = "";
for(User u: list) {
res += u.toString() + ", ";
}

resultFilter.setText(res);

}
});

/* */
}

/* */

HBox filters = new HBox();
ComboBox<String> ageFilterBox = new ComboBox<>();
ComboBox<String> salaryFilterBox = new ComboBox<>();
ComboBox<String> relationshipFilterBox = new ComboBox<>();
Button filter = new Button("filter");
Text resultFilter = new Text();

/* */

}

Quick Review On How To Create a Simple GUI in JavaFX Main Photo 6

That’s all.


package company;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javafx.application.Application;
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.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class Company extends Application {

@Override
public void start(Stage primaryStage) throws Exception {

users.add(new User("Alice", 20, 150, false));
users.add(new User("Bob", 34, 300, true));
users.add(new User("Peter", 18, 100, false));
users.add(new User("Kate", 38, 300, true));
users.add(new User("Steve", 31, 250, true));
users.add(new User("Alan", 62, 500, true));
users.add(new User("Julia", 33, 320, true));
users.add(new User("Patric", 37, 300, true));
users.add(new User("Alexander", 34, 280, true));
users.add(new User("George", 28, 180, true));
users.add(new User("Mary", 22, 190, false));

userBox.getItems().addAll(users);

ageFilterBox.getItems().addAll(
"no matter",
"over 20",
"over 30",
"over 40"
);

salaryFilterBox.getItems().addAll(
"no matter",
"over 150",
"over 250",
"over 500"
);

relationshipFilterBox.getItems().addAll(
"no matter",
"married",
"single"
);

root.getChildren().add(strings);

strings.setPadding(new Insets(10, 30, 10, 30));
strings.setSpacing(20);

strings.getChildren().add(new Text("Select the user"));
strings.getChildren().add(buttonBox);
strings.getChildren().add(new Text("Change the salary"));
strings.getChildren().add(changeSalaryBox);
strings.getChildren().add(new Text("Add new User"));
strings.getChildren().add(addUserBox);
strings.getChildren().add(filters);
strings.getChildren().add(resultFilter);

buttonBox.setSpacing(10);
buttonBox.getChildren().add(userBox);
buttonBox.getChildren().add(buttonGetInfo);
buttonBox.getChildren().add(textInfo);

changeSalaryBox.setSpacing(10);
changeSalaryBox.getChildren().add(buttonChangeSalary);
changeSalaryBox.getChildren().add(howMuchChange);

addUserBox.setSpacing(10);
addUserBox.getChildren().add(new Text("Name: "));
addUserBox.getChildren().add(name);
addUserBox.getChildren().add(new Text("Age: "));
addUserBox.getChildren().add(age);
addUserBox.getChildren().add(new Text("Salary: "));
addUserBox.getChildren().add(salary);
addUserBox.getChildren().add(new Text("Married: "));
addUserBox.getChildren().add(married);
addUserBox.getChildren().add(buttonAddUser);

filters.setSpacing(10);
filters.getChildren().add(new Text("Age"));
filters.getChildren().add(ageFilterBox);
filters.getChildren().add(new Text("Salary"));
filters.getChildren().add(salaryFilterBox);
filters.getChildren().add(new Text("Relationship"));
filters.getChildren().add(relationshipFilterBox);
filters.getChildren().add(filter);

Scene scene = new Scene(root, WIDTH, HEIGHT);
primaryStage.setTitle("Company");
primaryStage.setScene(scene);
primaryStage.show();

buttonGetInfo.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
User u = (User) userBox.getSelectionModel().getSelectedItem();
if (u != null) {
textInfo.setText("Age is " + u.getAge() + ", " +
"Salary is " + u.getSalary() + ", " +
"Relationship: " + u.getMarried());
} else {
textInfo.setText("User not selected");
}
}
});

buttonChangeSalary.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {

User u = (User) userBox.getSelectionModel().getSelectedItem();
if(u != null) {
u.changeSalary(Integer.parseInt(howMuchChange.getText()));
textInfo.setText("Age is " + u.getAge() + ", " +
"Salary is " + u.getSalary() + ", " +
"Relationshp: " + u.getMarried());
howMuchChange.clear();
}
}
});

buttonAddUser.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
String m = married.getText();
boolean mm = (m.equals("married"))? true:false;
User u = new User(name.getText(), Integer.parseInt(age.getText()),
Integer.parseInt(salary.getText()), mm);
users.add(u);
userBox.getItems().addAll(u);
name.clear();
age.clear();
salary.clear();
married.clear();
}
});

filter.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
int age;
int index = ageFilterBox.getSelectionModel().getSelectedIndex();
age = (index == 0)? 0: (index == 1)? 21: (index == 2)? 31: 41;

int salary;
index = salaryFilterBox.getSelectionModel().getSelectedIndex();
salary = (index == 0)? 0 : (index == 1)? 151 : (index == 2)? 251:501;

boolean relate;
index = relationshipFilterBox.getSelectionModel().getSelectedIndex();
relate = (index == 1)? true: (index == 2)? false: true;

//resultFilter.setText(String.valueOf(age) + " " + String.valueOf(salary) + " "+ relate);

List<User> list;
if(index != 0) { list = users.stream().
filter(u -> u.age > age).
filter(u -> u.salary > salary).
filter(u -> u.married == relate).
collect(Collectors.toList()); }

else { list = users.stream().
filter(u -> u.age > age).
filter(u -> u.salary > salary).
collect(Collectors.toList()); }

String res = "";
for(User u: list) {
res += u.toString() + ", ";
}

resultFilter.setText(res);

}
});

}

public static void main(String[] args) {
launch(args);
}

Group root = new Group();

VBox strings = new VBox();

HBox buttonBox = new HBox();
HBox changeSalaryBox = new HBox();
HBox addUserBox = new HBox();
HBox filters = new HBox();

ComboBox<User> userBox = new ComboBox<>();
ComboBox<String> ageFilterBox = new ComboBox<>();
ComboBox<String> salaryFilterBox = new ComboBox<>();
ComboBox<String> relationshipFilterBox = new ComboBox<>();

final private int WIDTH = 1000;
final private int HEIGHT = 600;

private ArrayList<User> users = new ArrayList<>();

Button buttonGetInfo = new Button("Info");
Text textInfo = new Text();

Button buttonChangeSalary = new Button("Change salary");
TextField howMuchChange = new TextField();

Button buttonAddUser = new Button("Add User");
TextField name = new TextField();
TextField age = new TextField();
TextField salary = new TextField();
TextField married = new TextField();

Button filter = new Button("filter");
Text resultFilter = new Text();

}


package company;

public class User {

User(String name, int age, int salary, boolean married) {
this.name = name;
this.age = age;
this.salary = salary;
this.married = married;
}

public void changeSalary(int x) {
salary = (salary + x <= 0)? 0: salary + x;
}

public String toString() {
return name;
}

public String getAge() {
return String.valueOf(age);
}

public String getSalary() {
return String.valueOf(salary);
}
public String getMarried() {
return (married)? ("married"):("single");
}

String name;
int age;
int salary;
boolean married;
}

Conclusion

The program itself does not represent any usefulness and was written solely in order to get acquainted with JavaFX and its tools. In some places, for example, when changing salaries, options are not taken into account when the user is not selected, or when a line is entered: in these cases, an error will appear. The same applies to fields where information is entered when new employees are added. And, finally, an error will occur if no value is selected in any of the drop-down lists. If desired, everyone can add their “bypass” of these moments.

When writing filters, by the way, we used the notorious StreamAPI and -expressions that shorten the code, add to it the ease of understanding and its charm.

References: