SlideShare a Scribd company logo
1 of 201
Download to read offline
Build 3 JavaFX Apps
Real-world, modern-looking GUIs with JavaFX
Marius Claassen,
Build 3 JavaFX Apps
About me
Marius Claassen, Java Expert and Teacher
I taught myself to program using Java. Having been a teacher for many
years, I am now working full-time as an independent software
instructor, making video tutorials. My passions are learning, teaching
and Java in equal measure. It is my mission to help others learn
programming in general and Java-related software in particular.
2
Marius Claassen,
Build 3 JavaFX Apps
Benefits
• Build applications in JavaFX
• Create a portfolio of working Apps
• Implement the MVC pattern
• Analyse Business requirements
• Devise JavaFX solutions
• Develop real-world apps
3
Marius Claassen,
Build 3 JavaFX Apps
Major components
• Introduction
• Airline App
• Health Centre App
• Real Estate App
• Conclusion
4
Marius Claassen,
Build 3 JavaFX Apps
Development tools
• JDK (SE10)
http://www.oracle.com/technetwork/java/javase/downloads/jdk10-downloads-4416644.html
• IDE (IntelliJ IDEA)
https://www.jetbrains.com/idea/download/#section=windows
• Scene Builder
http://gluonhq.com/products/scene-builder/thanks/?dl=/download/scene-builder-9-windows-x64/
5
Marius Claassen,
Build 3 JavaFX Apps
Ideal student
Completed intermediate course
You want to build modern Apps
6
Marius Claassen,
Build 3 JavaFX Apps
Enrolment
• 30-day money back guarantee
7
Marius Claassen,
Build 3 JavaFX Apps
Major components
 Introduction
• Airline App
• Health Centre App
• Real Estate App
• Conclusion
8
Marius Claassen,
Build 3 JavaFX Apps
Lecture 2: Airline App - Design
Problem statement:
Design the graphical user interface of an
airline App
9
Marius Claassen,
Build 3 JavaFX Apps
10
Marius Claassen,
Build 3 JavaFX Apps
Lecture 3: Airline App - Style
Problem statement:
Add style to the design of the Airline App
11
Marius Claassen,
Build 3 JavaFX Apps
Lecture 3: Airline App - Style
.mainContainer {
-fx-background-color: linear-gradient(aliceblue, lightblue, aliceblue);
}
.labelPrimary {
-fx-font-family: "Century Gothic";
-fx-font-size: 20;
-fx-font-weight: bold;
}
12
Marius Claassen,
Build 3 JavaFX Apps
.labelsSecondary {
-fx-font-family: "Century Gothic";
-fx-font-size: 12;
-fx-font-weight: bold;
}
13
Marius Claassen,
Build 3 JavaFX Apps
.buttons {
-fx-background-color: black;
-fx-background-radius: 50;
-fx-font-family: "Century Gothic";
-fx-font-size: 13;
-fx-text-fill: white;
-fx-font-weight: bold;
}
14
Marius Claassen,
Build 3 JavaFX Apps
.labelOutput {
-fx-background-color: white;
-fx-font-family: "Century Gothic";
-fx-font-size: 13;
-fx-text-fill: black;
-fx-font-weight: bold;
}
15
Marius Claassen,
Build 3 JavaFX Apps
16
Marius Claassen,
Build 3 JavaFX Apps
Lecture 4: Airline App – Code 1
Problem statement:
Implement code to check if a passenger’s
boarding is confirmed
17
Marius Claassen,
Build 3 JavaFX Apps
Lecture 4: Airline App – Code 1
package javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
18
Marius Claassen,
Build 3 JavaFX Apps
public class AirlineApp extends Application {
@Override public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("AirlineView.fxml"));
primaryStage.setTitle("JavaFX Airline App");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
19
Marius Claassen,
Build 3 JavaFX Apps
Lecture 4: Airline App – Code 1
package javafx;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.net.URL;
import java.time.LocalTime;
import java.util.ResourceBundle;
20
Marius Claassen,
Build 3 JavaFX Apps
public class AirlineController implements Initializable {
@FXML private TextField textFieldPassengerAge;
@FXML private CheckBox checkBoxPassport;
@FXML private Label labelPassenger;
@FXML private Button buttonPassenger;
21
Marius Claassen,
Build 3 JavaFX Apps
@FXML private void passengerButtonClick(ActionEvent event) {
int age = Integer.parseInt(textFieldPassengerAge.getText());
buttonPassenger.setOnAction(e -> {
if ((age >= 16) && (event.getSource() == checkBoxPassport)) {
labelPassenger.setText(" Boarding confirmed");
} else if ((age < 16) && (event.getSource() == checkBoxPassport)) {
labelPassenger.setText(" Boarding not confirmed");
} else { labelPassenger.setText(" Boarding confirmed"); }
});
}
22
Marius Claassen,
Build 3 JavaFX Apps
23
Marius Claassen,
Build 3 JavaFX Apps
24
Marius Claassen,
Build 3 JavaFX Apps
25
Marius Claassen,
Build 3 JavaFX Apps
Lecture 5: Airline App – Code 2
Problem statement:
Implement code to process a passenger’s
luggage
26
Marius Claassen,
Build 3 JavaFX Apps
Lecture 5: Airline App – Code 2
package javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
27
Marius Claassen,
Build 3 JavaFX Apps
public class AirlineApp extends Application {
@Override public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("AirlineView.fxml"));
primaryStage.setTitle("JavaFX Airline App");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
28
Marius Claassen,
Build 3 JavaFX Apps
Lecture 5: Airline App – Code 2
package javafx;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.net.URL;
import java.time.LocalTime;
import java.util.ResourceBundle;
29
Marius Claassen,
Build 3 JavaFX Apps
public class AirlineController implements Initializable {
private static final double EXCESS_RATE_PER_KG = 5.00;
@FXML private TextField textFieldLuggageWeight;
@FXML private ListView<String> listViewAirlines;
@FXML private TextArea textAreaLuggage;
@FXML private Button buttonLuggage;
30
Marius Claassen,
Build 3 JavaFX Apps
@Override public void initialize(URL location, ResourceBundle rb) {
listViewAirlines.setItems(FXCollections.observableArrayList(
"AA#23kg", "DL#32kg", "AI#25kg", "LO#32kg", "TG#50kg",
"PK#30kg"));
}
31
Marius Claassen,
Build 3 JavaFX Apps
@FXML private void luggageButtonClick() {
double luggageWeight =
Double.parseDouble(textFieldLuggageWeight.getText());
String airline =
listViewAirlines.getSelectionModel().getSelectedItem();
String str = airline.substring(3,5);
double maxWeight = Double.parseDouble(str);
double excessWeight = luggageWeight - maxWeight;
double costOfLuggage = excessWeight*EXCESS_RATE_PER_KG;
32
Marius Claassen,
Build 3 JavaFX Apps
if (excessWeight <= 0) {
excessWeight = 0;
costOfLuggage = 0;
}
String luggageCost = "Excess weight: "
.concat(String.format("%.2f kgn", excessWeight))
.concat("Cost: $ ")
.concat(String.format("%.2f", costOfLuggage));
buttonLuggage.setOnAction(e ->
textAreaLuggage.setText(luggageCost)); } }
33
Marius Claassen,
Build 3 JavaFX Apps
34
Marius Claassen,
Build 3 JavaFX Apps
35
Marius Claassen,
Build 3 JavaFX Apps
Lecture 6: Airline App – Code 3
Problem statement:
Implement code to process the airline meals
36
Marius Claassen,
Build 3 JavaFX Apps
Lecture 6: Airline App – Code 3
package javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
37
Marius Claassen,
Build 3 JavaFX Apps
public class AirlineApp extends Application {
@Override public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("AirlineView.fxml"));
primaryStage.setTitle("JavaFX Airline App");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
38
Marius Claassen,
Build 3 JavaFX Apps
Lecture 6: Airline App – Code 3
package javafx;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.net.URL;
import java.time.LocalTime;
import java.util.ResourceBundle;
39
Marius Claassen,
Build 3 JavaFX Apps
public class AirlineController implements Initializable {
@FXML private TextField textFieldNumPassengers;
@FXML private TextArea textAreaMeals;
@FXML private Button buttonMeals;
40
Marius Claassen,
Build 3 JavaFX Apps
@FXML private void mealsButtonClick() {
int totalMeals = Integer.parseInt(textFieldNumPassengers.getText());
double vegetarianMeals = totalMeals / 3;
double nonVegetarianMeals = totalMeals - vegetarianMeals;
String mealDistribution = "Vegetarian: "
.concat(String.format("%.0fn", vegetarianMeals))
.concat("Non-vegetarian: ")
.concat(String.format("%.0f", nonVegetarianMeals));
buttonMeals.setOnAction(e -> textAreaMeals.setText(mealDistribution)); } }
41
Marius Claassen,
Build 3 JavaFX Apps
42
Marius Claassen,
Build 3 JavaFX Apps
43
Marius Claassen,
Build 3 JavaFX Apps
Lecture 7: Airline App – Code 4
Problem statement:
Implement code to process departure and
boarding times
44
Marius Claassen,
Build 3 JavaFX Apps
Lecture 7: Airline App – Code 4
package javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
45
Marius Claassen,
Build 3 JavaFX Apps
public class AirlineApp extends Application {
@Override public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("AirlineView.fxml"));
primaryStage.setTitle("JavaFX Airline App");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
46
Marius Claassen,
Build 3 JavaFX Apps
Lecture 7: Airline App – Code 4
package javafx;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.net.URL;
import java.time.LocalTime;
import java.util.ResourceBundle;
47
Marius Claassen,
Build 3 JavaFX Apps
public class AirlineController implements Initializable {
@FXML private TextField textFieldDepartureTime;
@FXML private Label labelBoardingTime;
@FXML private Button buttonDeparture;
48
Marius Claassen,
Build 3 JavaFX Apps
@FXML private void departureButtonClick() {
buttonDeparture.setOnAction(e -> {
if (departureTimeValidated()) {
String depart = textFieldDepartureTime.getText();
LocalTime departureTime = LocalTime.parse(depart);
LocalTime boardingTime = departureTime.minusMinutes(45);
labelBoardingTime.setText(boardingTime.toString());
}
}); }
49
Marius Claassen,
Build 3 JavaFX Apps
private boolean departureTimeValidated() {
if (textFieldDepartureTime.getText().isEmpty()) {
Alert alert = new Alert(Alert.AlertType.ERROR, "Enter departure
time");
alert.setTitle("");
alert.setHeaderText("");
alert.showAndWait();
return false;
}
return true; } }
50
Marius Claassen,
Build 3 JavaFX Apps
51
Marius Claassen,
Build 3 JavaFX Apps
52
Marius Claassen,
Build 3 JavaFX Apps
53
Marius Claassen,
Build 3 JavaFX Apps
54
Marius Claassen,
Build 3 JavaFX Apps
Lecture 8: Airline App – Code 5
Problem statement:
Implement code to process frequent flyer
points earned
55
Marius Claassen,
Build 3 JavaFX Apps
Lecture 8: Airline App – Code 5
package javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
56
Marius Claassen,
Build 3 JavaFX Apps
public class AirlineApp extends Application {
@Override public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("AirlineView.fxml"));
primaryStage.setTitle("JavaFX Airline App");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
57
Marius Claassen,
Build 3 JavaFX Apps
Lecture 8: Airline App – Code 5
package javafx;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.net.URL;
import java.time.LocalTime;
import java.util.ResourceBundle;
58
Marius Claassen,
Build 3 JavaFX Apps
public class AirlineController implements Initializable {
private ToggleGroup toggleGroup = new ToggleGroup();
59
Marius Claassen,
Build 3 JavaFX Apps
@FXML private TextField textFieldKmsTraveled;
@FXML private RadioButton radioBtnSilver;
@FXML private RadioButton radioBtnGold;
@FXML private RadioButton radioBtnPlatinum;
@FXML private ImageView imageViewFlyerBenefits;
@FXML private Label labelPointsEarned;
@FXML private Button buttonFlyerFrequency;
60
Marius Claassen,
Build 3 JavaFX Apps
@Override public void initialize(URL location,
ResourceBundle rb) {
private Image image = new Image("file:C:/Users/mariuscn/
IdeaProjects /airlineapp/src/javafx/" +
"images/NonMember.jpg");
61
Marius Claassen,
Build 3 JavaFX Apps
imageViewFlyerBenefits.setImage(image);
radioBtnSilver.setToggleGroup(toggleGroup);
radioBtnGold.setToggleGroup(toggleGroup);
radioBtnPlatinum.setToggleGroup(toggleGroup);
labelPointsEarned.setText("Points earned: 0");
}
62
Marius Claassen,
Build 3 JavaFX Apps
@FXML public void frequentFlyerButtonClick() {
String kmsTraveled = textFieldKmsTraveled.getText();
double kms = Double.parseDouble(kmsTraveled);
63
Marius Claassen,
Build 3 JavaFX Apps
if (toggleGroup.getSelectedToggle().equals(radioBtnSilver)) {
imageViewFlyerBenefits.setImage(new Image(
"file:C:/Users/mariuscn/IdeaProjects/airlineapp/src/javafx/images/Silver.jpg"));
kms = Math.floor(kms / 1.6);
} else if (toggleGroup.getSelectedToggle().equals(radioBtnGold)) {
imageViewFlyerBenefits.setImage(new Image(
"file:C:/Users/mariuscn/IdeaProjects/airlineapp/src/javafx/images/Gold.jpg"));
kms = kms * 0.15 + (Math.floor(kms / 1.6)); }
64
Marius Claassen,
Build 3 JavaFX Apps
else { imageViewFlyerBenefits.setImage(new Image(
"file:C:/Users/mariuscn/IdeaProjects/airlineapp/src/javafx /images/Platinum.jpg"));
kms = kms * 0.20 + (Math.floor(kms / 1.6)); }
String pointsEarned = "Points earned: "
.concat(String.format("%.0f", kms));
buttonFlyerFrequency.setOnAction(e ->
labelPointsEarned.setText(pointsEarned)); } }
65
Marius Claassen,
Build 3 JavaFX Apps
66
Marius Claassen,
Build 3 JavaFX Apps
67
Marius Claassen,
Build 3 JavaFX Apps
Major components
 Introduction
 Airline App
• Health Centre App
• Real Estate App
• Conclusion
68
Marius Claassen,
Build 3 JavaFX Apps
Lecture 9: Health centre - Design
Problem statement:
Design the graphical user interface of a
Health Centre App
69
Marius Claassen,
Build 3 JavaFX Apps
70
Marius Claassen,
Build 3 JavaFX Apps
Lecture 10: Health centre - Style
Problem statement:
Add style to the design of the Health Centre
App
71
Marius Claassen,
Build 3 JavaFX Apps
Lecture 10: Health centre - Style
.mainContainer {
-fx-background-color: linear-gradient(violet, pink, violet);
}
.labelPrimary {
-fx-font-family: "Century Gothic";
-fx-font-size: 20;
-fx-font-weight: bold;
}
72
Marius Claassen,
Build 3 JavaFX Apps
.labelsSecondary {
-fx-font-family: "Century Gothic";
-fx-font-size: 12;
-fx-font-weight: bold;
}
73
Marius Claassen,
Build 3 JavaFX Apps
.buttons {
-fx-background-color: purple;
-fx-background-radius: 50;
-fx-font-family: "Century Gothic";
-fx-font-size: 13;
-fx-text-fill: white;
-fx-font-weight: bold;
}
74
Marius Claassen,
Build 3 JavaFX Apps
.labelsOutput {
-fx-background-color: white;
-fx-font-family: "Century Gothic";
-fx-font-size: 13;
-fx-text-fill: black;
-fx-font-weight: bold;
}
75
Marius Claassen,
Build 3 JavaFX Apps
76
Marius Claassen,
Build 3 JavaFX Apps
Lecture 11: Health centre – Code 1
Problem statement:
Implement code to calculate the amount
payable to a health plan
77
Marius Claassen,
Build 3 JavaFX Apps
Lecture 11: Health centre – Code 1
package javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
78
Marius Claassen,
Build 3 JavaFX Apps
public class HealthCentreApp extends Application {
@Override public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource(“HealthCentreView.fxml"));
primaryStage.setTitle("JavaFX Health Centre App");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
79
Marius Claassen,
Build 3 JavaFX Apps
Lecture 11: Health centre – Code 1
package javafx;
import javafx.collections.FXCollections;
import javafxcollections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import java.net.URL;
import java.time.LocalTime;
import java.util.ResourceBundle;
80
Marius Claassen,
Build 3 JavaFX Apps
public class HealthCentreController implements Initializable {
private static final double Y_CONTRIBUTION_RATE = 70;
private static final double C_CONTRIBUTION_RATE =
Y_CONTRIBUTION_RATE * 1.1;
private static final double L_CONTRIBUTION_RATE =
C_CONTRIBUTION_RATE * 1.1;
private static final double M_CONTRIBUTION_RATE =
L_CONTRIBUTION_RATE * 1.1;
81
Marius Claassen,
Build 3 JavaFX Apps
@FXML private ListView<String> listViewHealthPlans;
@FXML private TextField textFieldDependants;
@FXML private Button buttonHealthPlans;
82
Marius Claassen,
Build 3 JavaFX Apps
@Override public void initialize(URL location, ResourceBundle rb) {
textFieldDependants.setText("");
listViewHealthPlans.setItems(FXCollections.observableArrayList(
“Option Yud", “Option Chaf", “Option Lamed", “Option Mem"));
}
83
Marius Claassen,
Build 3 JavaFX Apps
@FXML private void healthPlanButtonClick() {
buttonHealthPlans.setOnAction(e -> {
if (validHealthPlan()) {
String plan =
listViewHealthPlans.getSelectionModel().getSelectedItem();
int dependants = Integer.parseInt(textFieldDependants.getText());
double = contribution;
84
Marius Claassen,
Build 3 JavaFX Apps
switch (plan) {
case "Option Yud": contribution =
Y_CONTRIBUTION_RATE + (dependants * 0.5 * Y_CONTRIBUTION_RATE); break;
case "Option Chaf": contribution =
C_CONTRIBUTION_RATE + (dependants * 0.5 * C_CONTRIBUTION_RATE); break;
case "Option Lamed": contribution =
L_CONTRIBUTION_RATE + (dependants * 0.5 * L_CONTRIBUTION_RATE); break;
default: contribution =
M_CONTRIBUTION_RATE + (dependants * 0.5 * M_CONTRIBUTION_RATE); break; }
85
Marius Claassen,
Build 3 JavaFX Apps
String result = String.format("%.2f", contribution);
Alert alert = new Alert(Alert.AlertType.INFORMATION,
"Monthly payment: $" + result);
alert.setTitle("");
alert.setHeaderText("");
alert.show(); } }); }
86
Marius Claassen,
Build 3 JavaFX Apps
private boolean validHealthPlan() {
if (textFieldDependants.getText().isEmpty() ||
(listViewHealthPlans.getSelectionModel().getSelectedItem().isEmpty())) {
Alert alert = new Alert(Alert.AlertType.ERROR,
"Select health plan and enter number of dependants");
alert.setTitle("");
alert.setHeaderText("");
alert.showAndWait();
return false; }
return true; } }
87
Marius Claassen,
Build 3 JavaFX Apps
88
Marius Claassen,
Build 3 JavaFX Apps
89
Marius Claassen,
Build 3 JavaFX Apps
90
Marius Claassen,
Build 3 JavaFX Apps
Lecture 12: Health centre – Code 2
Problem statement:
Implement code to process a payment
schedule for 12 months
91
Marius Claassen,
Build 3 JavaFX Apps
Lecture 12: Health centre – Code 2
package javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
92
Marius Claassen,
Build 3 JavaFX Apps
public class HealthCentreApp extends Application {
@Override public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource(“HealthCentreView.fxml"));
primaryStage.setTitle("JavaFX Health Centre App");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
93
Marius Claassen,
Build 3 JavaFX Apps
Lecture 12: Health centre – Code 2
package javafx;
import javafx.collections.FXCollections;
import javafxcollections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import java.net.URL;
import java.time.LocalTime;
import java.util.ResourceBundle;
94
Marius Claassen,
Build 3 JavaFX Apps
public class HealthCentreController implements Initializable {
private int paymentNo;
@FXML private TextField textFieldBalance;
@FXML private TableView<Payment> tableViewPmtSchedule;
@FXML private TableColumn<Payment, Integer>
tableColumnNumber;
@FXML private TableColumn<Payment, Integer>
tableColumnPayment;
@FXML private TableColumn<Payment, Integer>
tableColumnBalance;
@FXML private Button buttonPayment;
95
Marius Claassen,
Build 3 JavaFX Apps
@Override public void initialize(URL location, ResourceBundle rb) {
textFieldBalance.setText("");
}
96
Marius Claassen,
Build 3 JavaFX Apps
@FXML private void paymentButtonClick() {
int totalOwed = Integer.parseInt(textFieldBalance.getText());
int payment1 = Math.incrementExact((int) (totalOwed *.15));
int balance1 = Math.decrementExact(totalOwed - payment1);
int amtPerMonth = Math.round(balance1 / 11);
int balance2 = Math.round(balance1 - amtPerMonth);
97
Marius Claassen,
Build 3 JavaFX Apps
tableColumnNumber.setCellValueFactory(new PropertyValueFactory<>("paymentNumber"));
tableColumnPayment.setCellValueFactory(new PropertyValueFactory<>("monthlyPayment"));
tableColumnBalance.setCellValueFactory(new PropertyValueFactory<>("amountOwed"));
buttonPayment.setOnAction(e -> {
paymentNo = 0;
final ObservableList<Payment> data = FXCollections.observableArrayList(
new Payment(++paymentNo, payment1, balance1),
new Payment(++paymentNo, amtPerMonth, balance2),
new Payment(++paymentNo, amtPerMonth, balance2-amtPerMonth),
new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*2)),
new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*3)),
98
Marius Claassen,
Build 3 JavaFX Apps
new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*4)),
new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*5)),
new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*6)),
new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*7)),
new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*8)),
new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*9)),
new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*10))
);
tableViewPmtSchedule.setItems(data);
}); } }
99
Marius Claassen,
Build 3 JavaFX Apps
package javafx;
import javafx.beans.property.SimpleIntegerProperty;
public class Payment {
private SimpleIntegerProperty paymentNumber;
private final SimpleIntegerProperty monthlyPayment;
private final SimpleIntegerProperty amountOwed;
100
Marius Claassen,
Build 3 JavaFX Apps
public Payment(int paymentNo, int monthlyPayment, int amountOwed) {
this.paymentNumber = new SimpleIntegerProperty(paymentNo);
this.monthlyPayment = new
SimpleIntegerProperty(monthlyPayment);
this.amountOwed = new SimpleIntegerProperty(amountOwed);
}
101
Marius Claassen,
Build 3 JavaFX Apps
public int getPaymentNumber() {
return paymentNumber.get(); }
public SimpleIntegerProperty paymentNumberProperty() {
return paymentNumber; }
public void setPaymentNumber(int paymentNumber) {
this.paymentNumber.set(paymentNumber); }
102
Marius Claassen,
Build 3 JavaFX Apps
public int getMonthlyPayment() {
return monthlyPayment.get(); }
public SimpleIntegerProperty monthlyPaymentProperty() {
return monthlyPayment; }
public void setMonthlyPayment(int monthlyPayment) {
this.monthlyPayment.set(monthlyPayment); }
103
Marius Claassen,
Build 3 JavaFX Apps
public int getAmountOwed() {
return amountOwed.get(); }
public SimpleIntegerProperty amountOwedProperty() {
return amountOwed; }
public void setAmountOwed(int amountOwed) {
this.amountOwed.set(amountOwed); } }
104
Marius Claassen,
Build 3 JavaFX Apps
105
Marius Claassen,
Build 3 JavaFX Apps
Lecture 13: Health centre – Code 3
Problem statement:
Implement code to allocate patients to each
doctor
106
Marius Claassen,
Build 3 JavaFX Apps
Lecture 13: Health centre – Code 3
package javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
107
Marius Claassen,
Build 3 JavaFX Apps
public class HealthCentreApp extends Application {
@Override public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource(“HealthCentreView.fxml"));
primaryStage.setTitle("JavaFX Health Centre App");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
108
Marius Claassen,
Build 3 JavaFX Apps
Lecture 13: Health centre – Code 3
package javafx;
import javafx.collections.FXCollections;
import javafxcollections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import java.net.URL;
import java.time.LocalTime;
import java.util.ResourceBundle;
109
Marius Claassen,
Build 3 JavaFX Apps
public class HealthCentreController implements Initializable {
@FXML private TextField textFieldNumberOfPatients;
@FXML private Label labelDoctorTsade;
@FXML private Label labelDoctorKuf;
@FXML private Label labelDoctorReish;
@FXML private Button buttonDoctor;
110
Marius Claassen,
Build 3 JavaFX Apps
@Override public void initialize(URL location, ResourceBundle rb) {
textFieldNumberOfPatients.setText("");
}
111
Marius Claassen,
Build 3 JavaFX Apps
@FXML private void doctorButtonClick() {
int totalPatients =
Integer.parseInt(textFieldNumberOfPatients.getText());
int patientsPerDoctor = totalPatients / 3;
int remainder = totalPatients % 3;
int doctorTsade = patientsPerDoctor;
int doctorKuf = patientsPerDoctor;
112
Marius Claassen,
Build 3 JavaFX Apps
if (remainder == 2) {
doctorTsade++;
doctorKuf++;
} else {
doctorTsade++;
}
113
Marius Claassen,
Build 3 JavaFX Apps
String patientsDrTsade = String.format(" %d", doctorTsade);
String patientsDrKuf = String.format(" %d", doctorKuf);
String patientsDrReish = String.format(" %d", patientsPerDoctor);
buttonDoctor.setOnAction(e -> {
labelDoctorTsade.setText(patientsDrTsade);
labelDoctorKuf.setText(patientsDrKuf);
labelDoctorReish.setText(patientsDrReish);
} ); } }
114
Marius Claassen,
Build 3 JavaFX Apps
115
Marius Claassen,
Build 3 JavaFX Apps
116
Marius Claassen,
Build 3 JavaFX Apps
Lecture 14: Health centre – Code 4
Problem statement:
Implement code to process the doctors’
hours at work
117
Marius Claassen,
Build 3 JavaFX Apps
Lecture 14: Health centre – Code 4
package javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
118
Marius Claassen,
Build 3 JavaFX Apps
public class HealthCentreApp extends Application {
@Override public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource(“HealthCentreView.fxml"));
primaryStage.setTitle("JavaFX Health Centre App");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
119
Marius Claassen,
Build 3 JavaFX Apps
Lecture 14: Health centre – Code 4
package javafx;
import javafx.collections.FXCollections;
import javafxcollections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import java.net.URL;
import java.time.LocalTime;
import java.util.ResourceBundle;
120
Marius Claassen,
Build 3 JavaFX Apps
public class HealthCentreController implements Initializable {
private ToggleGroup toggleGroup = new ToggleGroup();
@FXML private TextField textFieldNumberOfPatients;
@FXML private Label labelDoctorTsade;
@FXML private Label labelDoctorKuf;
@FXML private Label labelDoctorReish;
@FXML private Button buttonDoctor;
121
Marius Claassen,
Build 3 JavaFX Apps
@FXML private TextField textFieldNumberOfMinutes;
@FXML private RadioButton radioButtonEight;
@FXML private RadioButton radioButtonEleven;
@FXML private RadioButton radioButtonThirteen;
@FXML private Label labelTimeAtWork;
@FXML private Label labelSignOutTime;
122
Marius Claassen,
Build 3 JavaFX Apps
@Override public void initialize(URL location, ResourceBundle rb) {
textFieldNumberOfPatients.setText("");
textFieldMinutesPerPatient.setText("");
}
123
Marius Claassen,
Build 3 JavaFX Apps
@FXML private void doctorButtonClick() {
int totalPatients =
Integer.parseInt(textFieldNumberOfPatients.getText());
int patientsPerDoctor = totalPatients / 3;
int remainder = totalPatients % 3;
int doctorTsade = patientsPerDoctor;
int doctorKuf = patientsPerDoctor;
124
Marius Claassen,
Build 3 JavaFX Apps
if (remainder == 2) {
doctorTsade++;
doctorKuf++;
} else {
doctorTsade++;
}
125
Marius Claassen,
Build 3 JavaFX Apps
int hours = 0;
int minutes;
int aveConsultationTime =
Integer.parseInt(textFieldNumberOfMinutes.getText());
int totalConsultationTime = doctorTsade * aveConsultationTime;
int hoursWorked = 0;
126
Marius Claassen,
Build 3 JavaFX Apps
if (totalConsultationTime < 60) {
minutes = totalConsultationTime;
hoursWorked++;
} else if (totalConsultationTime < 120) {
hours++;
minutes = totalConsultationTime - 60;
hoursWorked += 2;
} else if (totalConsultationTime < 180) {
hours += 2;
minutes = totalConsultationTime - 60;
hoursWorked += 3; }
127
Marius Claassen,
Build 3 JavaFX Apps
else if (totalConsultationTime < 240) {
hours += 3;
minutes = totalConsultationTime - 60;
hoursWorked += 4;
} else {
hours += 4;
minutes = totalConsultationTime - 60;
hoursWorked += 5;
}
128
Marius Claassen,
Build 3 JavaFX Apps
radioButtonEight.setToggleGroup(toggleGroup);
radioButtonEleven.setToggleGroup(toggleGroup);
radioButtonThirteen.setToggleGroup(toggleGroup);
LocalTime time1 = LocalTime.of(8,0);
LocalTime time2 = LocalTime.of(11,0);
LocalTime time3 = LocalTime.of(13,0);
final LocalTime signOut;
129
Marius Claassen,
Build 3 JavaFX Apps
if (toggleGroup.getSelectedToggle().equals(radioButtonEight)) {
signOut = time1.plusHours(hoursWorked);
} else if
(toggleGroup.getSelectedToggle().equals(radioButtonEleven)) {
signOut = time2.plusHours(hoursWorked);
} else {
signOut = time3.plusHours(hoursWorked);
}
130
Marius Claassen,
Build 3 JavaFX Apps
String patientsDrTsade = String.format(" %d", doctorTsade);
String patientsDrKuf = String.format(" %d", doctorKuf);
String patientsDrReish = String.format(" %d", patientsPerDoctor);
String timeAtWork = " "
.concat(String.format("%d", hours))
.concat(" hour(s)")
.concat(String.format(" %d", minutes))
.concat(" minutes");
131
Marius Claassen,
Build 3 JavaFX Apps
buttonDoctor.setOnAction(e -> {
labelDoctorTsade.setText(patientsDrTsade);
labelDoctorKuf.setText(patientsDrKuf);
labelDoctorReish.setText(patientsDrReish);
labelTimeAtWork.setText(timeAtWork);
labelSignOutTime.setText(signOut.toString());
} ); } }
132
Marius Claassen,
Build 3 JavaFX Apps
133
Marius Claassen,
Build 3 JavaFX Apps
134
Marius Claassen,
Build 3 JavaFX Apps
Major components
 Introduction
 Airline App
 Health Centre App
• Real Estate App
• Conclusion
135
Marius Claassen,
Build 3 JavaFX Apps
Lecture 15: Real estate - Design
Problem statement:
Design the graphical user interface of a Real
Estate App
136
Marius Claassen,
Build 3 JavaFX Apps
137
Marius Claassen,
Build 3 JavaFX Apps
138
Marius Claassen,
Build 3 JavaFX Apps
139
Marius Claassen,
Build 3 JavaFX Apps
Lecture 16: Real estate App - Style
Problem statement:
Add style to the design of the Real Estate App
140
Marius Claassen,
Build 3 JavaFX Apps
Lecture 16: Real estate App - Style
.mainContainer {
-fx-background-color: linear-gradient(gold, lemochiffon, gold);
}
.labelsPrimary {
-fx-font-family: "Century Gothic";
-fx-font-size: 17;
-fx-font-weight: bold;
}
141
Marius Claassen,
Build 3 JavaFX Apps
.labelsSecondary, .checkBox, .radioButtons {
-fx-font-family: "Century Gothic";
-fx-font-size: 16;
}
142
Marius Claassen,
Build 3 JavaFX Apps
.labelOutput {
-fx-background-color: white;
-fx-font-family: "Century Gothic";
-fx-font-size: 13;
-fx-text-fill: black;
-fx-font-weight: bold;
}
143
Marius Claassen,
Build 3 JavaFX Apps
.buttons {
-fx-background-color: orange;
-fx-background-radius: 50;
-fx-font-family: "Century Gothic";
-fx-font-size: 16;
-fx-text-fill: black;
-fx-font-weight: bold;
}
144
Marius Claassen,
Build 3 JavaFX Apps
145
Marius Claassen,
Build 3 JavaFX Apps
146
Marius Claassen,
Build 3 JavaFX Apps
147
Marius Claassen,
Build 3 JavaFX Apps
Lecture 17: Real estate – Code 1
Problem statement:
Implement code to generate an
advertisement
148
Marius Claassen,
Build 3 JavaFX Apps
Lecture 17: Real estate – Code 1
package javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
149
Marius Claassen,
Build 3 JavaFX Apps
public class RealEstateApp extends Application {
@Override public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource(“RealEstateViews.fxml"));
primaryStage.setTitle("JavaFX Real Estate App");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
150
Marius Claassen,
Build 3 JavaFX Apps
Lecture 17: Real estate – Code 1
package javafx;
import javafx.beans.binding.StringBinding;
import javafx.beans.binding.StringExpression;
import javafx.beans.binding.When;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import java.util.Optional;
151
Marius Claassen,
Build 3 JavaFX Apps
public class RealEstateController {
@FXML private TextField textFieldMarketValue;
@FXML private TextField textFieldSellingPrice;
@FXML private TextField textFieldNumberOfBedrooms;
@FXML private TextField textFieldNumberOfBathrooms;
@FXML private CheckBox checkBoxSwimmingPool;
@FXML private Button buttonAdvertisement;
@FXML private TextArea textAreaAdvertisement;
152
Marius Claassen,
Build 3 JavaFX Apps
@FXML public void advertisementButtonClick() {
StringProperty advert = new SimpleStringProperty("nHOUSE
FOR SALE:");
StringBinding swimmingPool = new When
(checkBoxSwimmingPool.selectedProperty())
.then("Swimming Pool")
.otherwise("");
153
Marius Claassen,
Build 3 JavaFX Apps
int marketValue =
Integer.parseInt(textFieldMarketValue.getText());
int sellingPrice =
Integer.parseInt(textFieldSellingPrice.getText());
int numberOfBedrooms =
Integer.parseInt(textFieldNumberOfBedrooms.getText());
int numberOfBathrooms =
Integer.parseInt(textFieldNumberOfBathrooms.getText());
String bargain = (sellingPrice < marketValue) ? "Bargain" : "";
154
Marius Claassen,
Build 3 JavaFX Apps
StringExpression advertisementDetails = advert
.concat("nSelling Price: $")
.concat(String.format("%d",sellingPrice))
.concat("nBedrooms: ")
.concat(String.format("%d", numberOfBedrooms))
.concat("nBathrooms: ")
.concat(String.format("%d", numberOfBathrooms))
.concat("n")
.concat(swimmingPool)
.concat("n")
.concat(bargain);
155
Marius Claassen,
Build 3 JavaFX Apps
buttonAdvertisement.setOnAction(e ->
textAreaAdvertisement.setText(advertisementDetails.getValue()));
}
}
156
Marius Claassen,
Build 3 JavaFX Apps
157
Marius Claassen,
Build 3 JavaFX Apps
158
Marius Claassen,
Build 3 JavaFX Apps
159
Marius Claassen,
Build 3 JavaFX Apps
Lecture 18: Real estate – Code 2
Problem statement:
Implement code to process renovations to
the living room
160
Marius Claassen,
Build 3 JavaFX Apps
Lecture 18: Real estate – Code 2
package javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
161
Marius Claassen,
Build 3 JavaFX Apps
public class RealEstateApp extends Application {
@Override public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource(“RealEstateViews.fxml"));
primaryStage.setTitle("JavaFX Real Estate App");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
162
Marius Claassen,
Build 3 JavaFX Apps
Lecture 18: Real estate – Code 2
package javafx;
import javafx.beans.binding.StringBinding;
import javafx.beans.binding.StringExpression;
import javafx.beans.binding.When;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import java.util.Optional;
163
Marius Claassen,
Build 3 JavaFX Apps
public class RealEstateController {
private static final double AREA_PER_LTR_PAINT = 8;
private static final double FIVE_LTR_COST = 18.70;
private static final double TWO_LTR_COST = 9.60;
private static final double ONE_LTR_COST = 5.45;
private static final int FIVE_LTR_DRUM = 5;
private static final int TWO_LTR_DRUM = 2;
private static final double TILE_BREAKAGES = 5;
164
Marius Claassen,
Build 3 JavaFX Apps
@FXML private TextField textFieldAreaToRenovate;
@FXML private RadioButton radioButtonPainting;
@FXML private RadioButton radioButtonTiling;
@FXML private Button buttonRenovationsCost;
@FXML private TextArea textAreaRenovationsCost;
165
Marius Claassen,
Build 3 JavaFX Apps
@FXML private void renovationsButtonClick() {
ToggleGroup toggleGroup = new ToggleGroup();
radioButtonPainting.setToggleGroup(toggleGroup);
radioButtonTiling.setToggleGroup(toggleGroup);
double areaToRenovate =
Double.parseDouble(textFieldAreaToRenovate.getText());
double volumeOfPaint = areaToRenovate /
AREA_PER_LTR_PAINT;
166
Marius Claassen,
Build 3 JavaFX Apps
int numberOfFiveLtrDrums = (int) volumeOfPaint /
FIVE_LTR_DRUM;
int numberOfTwoLtrDrums = (int)
Math.round((volumeOfPaint - (numberOfFiveLtrDrums *
FIVE_LTR_DRUM))) / 2;
int numberOfOneLtrDrums = (int) Math.round(volumeOfPaint
- (numberOfFiveLtrDrums * FIVE_LTR_DRUM) -
(numberOfTwoLtrDrums * TWO_LTR_DRUM));
167
Marius Claassen,
Build 3 JavaFX Apps
double costOfPaint = (numberOfFiveLtrDrums *
FIVE_LTR_COST)
+ (numberOfTwoLtrDrums * TWO_LTR_COST)
+ (numberOfOneLtrDrums * ONE_LTR_COST);
double tileCostPerSqMetre = 0;
double costOfTiles;
168
Marius Claassen,
Build 3 JavaFX Apps
if
(toggleGroup.getSelectedToggle().equals(radioButtonPainting
)) {
String paintingDetails = "nAREA TO PAINT:"
.concat(String.format("n%.0f", areaToRenovate))
.concat(" square metres")
.concat("nnVolume of paint required: ")
.concat(String.format("%.1f", volumeOfPaint))
.concat(" litres")
169
Marius Claassen,
Build 3 JavaFX Apps
.concat("n1-litre drums: ")
.concat(String.format("%d", numberOfOneLtrDrums))
.concat("n2-litre drums: ")
.concat(String.format("%d", numberOfTwoLtrDrums))
.concat("n5-litre drums: ")
.concat(String.format("%d", numberOfFiveLtrDrums))
.concat("nnTotal cost: $")
.concat(String.format("%.2f", costOfPaint));
170
Marius Claassen,
Build 3 JavaFX Apps
buttonRenovationsCost.setOnAction(e ->
textAreaRenovationsCost.setText(paintingDetails));
171
Marius Claassen,
Build 3 JavaFX Apps
} else {
TextInputDialog input = new TextInputDialog();
input.setTitle("");
input.setHeaderText("");
input.setContentText("Enter tiling cost per square metre");
input.showAndWait()
.ifPresent(str -> tileCostPerSqMetre[0] =
Double.parseDouble(str));
172
Marius Claassen,
Build 3 JavaFX Apps
costOfTiles = (areaToRenovate + TILE_BREAKAGES) * tileCostPerSqMetre[0];
String tilingDetails = "nAREA TO TILE:"
.concat(String.format("n%.0f", areaToRenovate))
.concat(" square metres")
.concat("nTotal cost: $")
.concat(String.format("%.2f",costOfTiles));
buttonRenovationsCost.setOnAction(e ->
textAreaRenovationsCost.setText(tilingDetails));
} } }
173
Marius Claassen,
Build 3 JavaFX Apps
174
Marius Claassen,
Build 3 JavaFX Apps
175
Marius Claassen,
Build 3 JavaFX Apps
176
Marius Claassen,
Build 3 JavaFX Apps
Lecture 19: Real estate – Code 3
Problem statement:
Implement code to calculate the electricity
amount payable
177
Marius Claassen,
Build 3 JavaFX Apps
Lecture 19: Real estate – Code 3
package javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
178
Marius Claassen,
Build 3 JavaFX Apps
public class RealEstateApp extends Application {
@Override public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource(“RealEstateViews.fxml"));
primaryStage.setTitle("JavaFX Real Estate App");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
179
Marius Claassen,
Build 3 JavaFX Apps
Lecture 19: Real estate – Code 3
package javafx;
import javafx.beans.binding.StringBinding;
import javafx.beans.binding.StringExpression;
import javafx.beans.binding.When;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import java.util.Optional;
180
Marius Claassen,
Build 3 JavaFX Apps
public class RealEstateController {
private static final int ELECTRICITY_LOWER_LIMIT_UNITS =
600;
private static final int
ELECTRICITY_LOWER_LIMIT_AMOUNT = 50;
private static final double ELECTRICITY_LOWER_TARIFF =
0.10;
private static final double ELECTRICITY_UPPER_TARIFF =
0.15;
181
Marius Claassen,
Build 3 JavaFX Apps
@FXML private TextField textFieldPreviousReading;
@FXML private TextField textFieldCurrentReading;
@FXML private Label labelElectricity;
@FXML private Button buttonElectricityAmount;
182
Marius Claassen,
Build 3 JavaFX Apps
@FXML private void electricityButtonClick() {
int previousReading =
Integer.parseInt(textFieldPreviousReading.getText());
int currentReading =
Integer.parseInt(textFieldCurrentReading.getText());
double amountDue;
183
Marius Claassen,
Build 3 JavaFX Apps
if (currentReading <= previousReading) {
Alert alert = new Alert(Alert.AlertType.ERROR,
"Enter current reading greater than previous reading");
alert.setTitle("");
alert.setHeaderText("");
alert.showAndWait();
textFieldCurrentReading.setText("");
184
Marius Claassen,
Build 3 JavaFX Apps
} else {
if ((currentReading - previousReading) <= ELECTRICITY_LOWER_LIMIT_UNITS) {
amountDue = (currentReading - previousReading) *
ELECTRICITY_LOWER_TARIFF;
} else {
amountDue = (ELECTRICITY_LOWER_LIMIT_AMOUNT +
(currentReading - (previousReading + ELECTRICITY_LOWER_LIMIT_UNITS))
* ELECTRICITY_UPPER_TARIFF);
}
String amount = " $".concat(String.format("%.2f", amountDue));
buttonElectricityAmount.setOnAction(e -> labelElectricity.setText(amount)); } } }
185
Marius Claassen,
Build 3 JavaFX Apps
186
Marius Claassen,
Build 3 JavaFX Apps
187
Marius Claassen,
Build 3 JavaFX Apps
188
Marius Claassen,
Build 3 JavaFX Apps
Lecture 20: Real estate – Code 4
Problem statement:
Implement code to display the size of geyser
matching the user input
189
Marius Claassen,
Build 3 JavaFX Apps
Lecture 20: Real estate – Code 4
package javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
190
Marius Claassen,
Build 3 JavaFX Apps
public class RealEstateApp extends Application {
@Override public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource(“RealEstateViews.fxml"));
primaryStage.setTitle("JavaFX Real Estate App");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
191
Marius Claassen,
Build 3 JavaFX Apps
Lecture 20: Real estate – Code 4
package javafx;
import javafx.beans.binding.StringBinding;
import javafx.beans.binding.StringExpression;
import javafx.beans.binding.When;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import java.util.Optional;
192
Marius Claassen,
Build 3 JavaFX Apps
public class RealEstateController {
private static final ObservableList<String> solarGeysers =
FXCollections.observableArrayList(
"50-BetSolar", "50-GimmelWonder", "50-DaletSun",
"100-BetSolar", "100-GimmelWonder", "100-DaletSun",
"150-BetSolar", "150-GimmelWonder", "150-DaletSun");
193
Marius Claassen,
Build 3 JavaFX Apps
@FXML private TextField textFieldGeyser;
@FXML private TextArea textAreaGeyser;
@FXML private Button buttonGeyser;
194
Marius Claassen,
Build 3 JavaFX Apps
@FXML private void geyserButtonClick() {
int geyserSize =
Integer.parseInt(textFieldGeyser.getText());
FilteredList<String> geyserList;
195
Marius Claassen,
Build 3 JavaFX Apps
if (geyserSize == 50) {
geyserList = solarGeysers.filtered(g ->
g.startsWith("50"));
} else if (geyserSize == 100) {
geyserList = solarGeysers.filtered(g ->
g.startsWith("100"));
} else {
geyserList = solarGeysers.filtered(g ->
g.startsWith("150"));
}
196
Marius Claassen,
Build 3 JavaFX Apps
FilteredList<String> finalGeyserList = geyserList;
buttonGeyser.setOnAction(e -> textAreaGeyser.setText(
String.format("%s", finalGeyserList)));
}
}
197
Marius Claassen,
Build 3 JavaFX Apps
198
Marius Claassen,
Build 3 JavaFX Apps
199
Marius Claassen,
Build 3 JavaFX Apps
To access this course:
• https://www.udemy.com/course/1474854/manage/basics/
or
• mariusclaassen@gmail.com
200
Marius Claassen,
Build 3 JavaFX Apps
Build 3 JavaFX Apps
Real-world, modern-looking GUIs with JavaFX
Marius Claassen,
Build 3 JavaFX Apps

More Related Content

Similar to Build 3 JavaFX Apps

Cloudcamp scotland - Using cloud without losing control
Cloudcamp scotland - Using cloud without losing controlCloudcamp scotland - Using cloud without losing control
Cloudcamp scotland - Using cloud without losing controlDuncan Johnston-Watt
 
load-testing-with-k6-nakov-at-qa-challenge-accepted-oct-2021-211002181104.pdf
load-testing-with-k6-nakov-at-qa-challenge-accepted-oct-2021-211002181104.pdfload-testing-with-k6-nakov-at-qa-challenge-accepted-oct-2021-211002181104.pdf
load-testing-with-k6-nakov-at-qa-challenge-accepted-oct-2021-211002181104.pdfobuleshuppara
 
Load Testing with k6 framework
Load Testing with k6 frameworkLoad Testing with k6 framework
Load Testing with k6 frameworkSvetlin Nakov
 
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...Codemotion
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenJoshua Long
 
Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02
Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02
Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02Rati Manandhar
 
JavaFX in Action (devoxx'16)
JavaFX in Action (devoxx'16)JavaFX in Action (devoxx'16)
JavaFX in Action (devoxx'16)Alexander Casall
 
Machine Learning on IBM Watson Studio
Machine Learning on IBM Watson StudioMachine Learning on IBM Watson Studio
Machine Learning on IBM Watson StudioUpkar Lidder
 
Spring Cloud Function — Going Serverless
Spring Cloud Function — Going ServerlessSpring Cloud Function — Going Serverless
Spring Cloud Function — Going ServerlessGlobalLogic Ukraine
 
Cloud Application Blueprints with Apache Brooklyn by Alex Henevald
Cloud Application Blueprints with Apache Brooklyn by Alex HenevaldCloud Application Blueprints with Apache Brooklyn by Alex Henevald
Cloud Application Blueprints with Apache Brooklyn by Alex Henevaldbuildacloud
 
iOS App Module Management
iOS App Module ManagementiOS App Module Management
iOS App Module ManagementRyan Wang
 
BOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsBOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsPeter Pilgrim
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015jbandi
 
JavaScript Modules Past, Present and Future
JavaScript Modules Past, Present and FutureJavaScript Modules Past, Present and Future
JavaScript Modules Past, Present and FutureIgalia
 
Reusing your frontend JS on the server with V8/Rhino
Reusing your frontend JS on the server with V8/RhinoReusing your frontend JS on the server with V8/Rhino
Reusing your frontend JS on the server with V8/RhinoKenneth Kalmer
 
Getting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafGetting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafMasatoshi Tada
 
Terraform introduction
Terraform introductionTerraform introduction
Terraform introductionJason Vance
 
MegaScriptSample - Released x-x-15
MegaScriptSample - Released x-x-15MegaScriptSample - Released x-x-15
MegaScriptSample - Released x-x-15Bob Powers
 

Similar to Build 3 JavaFX Apps (20)

Java for advanced users
Java for advanced usersJava for advanced users
Java for advanced users
 
Cursor Demo App
Cursor Demo AppCursor Demo App
Cursor Demo App
 
Cloudcamp scotland - Using cloud without losing control
Cloudcamp scotland - Using cloud without losing controlCloudcamp scotland - Using cloud without losing control
Cloudcamp scotland - Using cloud without losing control
 
load-testing-with-k6-nakov-at-qa-challenge-accepted-oct-2021-211002181104.pdf
load-testing-with-k6-nakov-at-qa-challenge-accepted-oct-2021-211002181104.pdfload-testing-with-k6-nakov-at-qa-challenge-accepted-oct-2021-211002181104.pdf
load-testing-with-k6-nakov-at-qa-challenge-accepted-oct-2021-211002181104.pdf
 
Load Testing with k6 framework
Load Testing with k6 frameworkLoad Testing with k6 framework
Load Testing with k6 framework
 
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in Heaven
 
Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02
Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02
Stepbystepguideforbuidlingsimplestrutsapp 090702025438-phpapp02
 
JavaFX in Action (devoxx'16)
JavaFX in Action (devoxx'16)JavaFX in Action (devoxx'16)
JavaFX in Action (devoxx'16)
 
Machine Learning on IBM Watson Studio
Machine Learning on IBM Watson StudioMachine Learning on IBM Watson Studio
Machine Learning on IBM Watson Studio
 
Spring Cloud Function — Going Serverless
Spring Cloud Function — Going ServerlessSpring Cloud Function — Going Serverless
Spring Cloud Function — Going Serverless
 
Cloud Application Blueprints with Apache Brooklyn by Alex Henevald
Cloud Application Blueprints with Apache Brooklyn by Alex HenevaldCloud Application Blueprints with Apache Brooklyn by Alex Henevald
Cloud Application Blueprints with Apache Brooklyn by Alex Henevald
 
iOS App Module Management
iOS App Module ManagementiOS App Module Management
iOS App Module Management
 
BOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsBOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala apps
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015
 
JavaScript Modules Past, Present and Future
JavaScript Modules Past, Present and FutureJavaScript Modules Past, Present and Future
JavaScript Modules Past, Present and Future
 
Reusing your frontend JS on the server with V8/Rhino
Reusing your frontend JS on the server with V8/RhinoReusing your frontend JS on the server with V8/Rhino
Reusing your frontend JS on the server with V8/Rhino
 
Getting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafGetting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with Thymeleaf
 
Terraform introduction
Terraform introductionTerraform introduction
Terraform introduction
 
MegaScriptSample - Released x-x-15
MegaScriptSample - Released x-x-15MegaScriptSample - Released x-x-15
MegaScriptSample - Released x-x-15
 

More from Marius Claassen

Java for intermediate users
Java for intermediate usersJava for intermediate users
Java for intermediate usersMarius Claassen
 
Java for beginners programming course
Java for beginners programming courseJava for beginners programming course
Java for beginners programming courseMarius Claassen
 
Java for intermediate users
Java for intermediate usersJava for intermediate users
Java for intermediate usersMarius Claassen
 
Java for beginners programming course (updated)
Java for beginners programming course (updated)Java for beginners programming course (updated)
Java for beginners programming course (updated)Marius Claassen
 
Java for complete beginners programming course
Java for complete beginners programming courseJava for complete beginners programming course
Java for complete beginners programming courseMarius Claassen
 
Java 8 for complete beginners
Java 8 for complete beginnersJava 8 for complete beginners
Java 8 for complete beginnersMarius Claassen
 
Java for Beginners Programming course
Java for Beginners Programming courseJava for Beginners Programming course
Java for Beginners Programming courseMarius Claassen
 
Java 8 for complete beginners programming course
Java 8 for complete beginners programming courseJava 8 for complete beginners programming course
Java 8 for complete beginners programming courseMarius Claassen
 

More from Marius Claassen (12)

What does apr mean
What does apr meanWhat does apr mean
What does apr mean
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Java, the basics
Java, the basicsJava, the basics
Java, the basics
 
Java for intermediate users
Java for intermediate usersJava for intermediate users
Java for intermediate users
 
Java for beginners programming course
Java for beginners programming courseJava for beginners programming course
Java for beginners programming course
 
Java overview
Java overview Java overview
Java overview
 
Java for intermediate users
Java for intermediate usersJava for intermediate users
Java for intermediate users
 
Java for beginners programming course (updated)
Java for beginners programming course (updated)Java for beginners programming course (updated)
Java for beginners programming course (updated)
 
Java for complete beginners programming course
Java for complete beginners programming courseJava for complete beginners programming course
Java for complete beginners programming course
 
Java 8 for complete beginners
Java 8 for complete beginnersJava 8 for complete beginners
Java 8 for complete beginners
 
Java for Beginners Programming course
Java for Beginners Programming courseJava for Beginners Programming course
Java for Beginners Programming course
 
Java 8 for complete beginners programming course
Java 8 for complete beginners programming courseJava 8 for complete beginners programming course
Java 8 for complete beginners programming course
 

Recently uploaded

Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answersdalebeck957
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 

Recently uploaded (20)

Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answers
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 

Build 3 JavaFX Apps

  • 1. Build 3 JavaFX Apps Real-world, modern-looking GUIs with JavaFX Marius Claassen, Build 3 JavaFX Apps
  • 2. About me Marius Claassen, Java Expert and Teacher I taught myself to program using Java. Having been a teacher for many years, I am now working full-time as an independent software instructor, making video tutorials. My passions are learning, teaching and Java in equal measure. It is my mission to help others learn programming in general and Java-related software in particular. 2 Marius Claassen, Build 3 JavaFX Apps
  • 3. Benefits • Build applications in JavaFX • Create a portfolio of working Apps • Implement the MVC pattern • Analyse Business requirements • Devise JavaFX solutions • Develop real-world apps 3 Marius Claassen, Build 3 JavaFX Apps
  • 4. Major components • Introduction • Airline App • Health Centre App • Real Estate App • Conclusion 4 Marius Claassen, Build 3 JavaFX Apps
  • 5. Development tools • JDK (SE10) http://www.oracle.com/technetwork/java/javase/downloads/jdk10-downloads-4416644.html • IDE (IntelliJ IDEA) https://www.jetbrains.com/idea/download/#section=windows • Scene Builder http://gluonhq.com/products/scene-builder/thanks/?dl=/download/scene-builder-9-windows-x64/ 5 Marius Claassen, Build 3 JavaFX Apps
  • 6. Ideal student Completed intermediate course You want to build modern Apps 6 Marius Claassen, Build 3 JavaFX Apps
  • 7. Enrolment • 30-day money back guarantee 7 Marius Claassen, Build 3 JavaFX Apps
  • 8. Major components  Introduction • Airline App • Health Centre App • Real Estate App • Conclusion 8 Marius Claassen, Build 3 JavaFX Apps
  • 9. Lecture 2: Airline App - Design Problem statement: Design the graphical user interface of an airline App 9 Marius Claassen, Build 3 JavaFX Apps
  • 11. Lecture 3: Airline App - Style Problem statement: Add style to the design of the Airline App 11 Marius Claassen, Build 3 JavaFX Apps
  • 12. Lecture 3: Airline App - Style .mainContainer { -fx-background-color: linear-gradient(aliceblue, lightblue, aliceblue); } .labelPrimary { -fx-font-family: "Century Gothic"; -fx-font-size: 20; -fx-font-weight: bold; } 12 Marius Claassen, Build 3 JavaFX Apps
  • 13. .labelsSecondary { -fx-font-family: "Century Gothic"; -fx-font-size: 12; -fx-font-weight: bold; } 13 Marius Claassen, Build 3 JavaFX Apps
  • 14. .buttons { -fx-background-color: black; -fx-background-radius: 50; -fx-font-family: "Century Gothic"; -fx-font-size: 13; -fx-text-fill: white; -fx-font-weight: bold; } 14 Marius Claassen, Build 3 JavaFX Apps
  • 15. .labelOutput { -fx-background-color: white; -fx-font-family: "Century Gothic"; -fx-font-size: 13; -fx-text-fill: black; -fx-font-weight: bold; } 15 Marius Claassen, Build 3 JavaFX Apps
  • 17. Lecture 4: Airline App – Code 1 Problem statement: Implement code to check if a passenger’s boarding is confirmed 17 Marius Claassen, Build 3 JavaFX Apps
  • 18. Lecture 4: Airline App – Code 1 package javafx; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; 18 Marius Claassen, Build 3 JavaFX Apps
  • 19. public class AirlineApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("AirlineView.fxml")); primaryStage.setTitle("JavaFX Airline App"); primaryStage.setScene(new Scene(root)); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 19 Marius Claassen, Build 3 JavaFX Apps
  • 20. Lecture 4: Airline App – Code 1 package javafx; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import java.net.URL; import java.time.LocalTime; import java.util.ResourceBundle; 20 Marius Claassen, Build 3 JavaFX Apps
  • 21. public class AirlineController implements Initializable { @FXML private TextField textFieldPassengerAge; @FXML private CheckBox checkBoxPassport; @FXML private Label labelPassenger; @FXML private Button buttonPassenger; 21 Marius Claassen, Build 3 JavaFX Apps
  • 22. @FXML private void passengerButtonClick(ActionEvent event) { int age = Integer.parseInt(textFieldPassengerAge.getText()); buttonPassenger.setOnAction(e -> { if ((age >= 16) && (event.getSource() == checkBoxPassport)) { labelPassenger.setText(" Boarding confirmed"); } else if ((age < 16) && (event.getSource() == checkBoxPassport)) { labelPassenger.setText(" Boarding not confirmed"); } else { labelPassenger.setText(" Boarding confirmed"); } }); } 22 Marius Claassen, Build 3 JavaFX Apps
  • 26. Lecture 5: Airline App – Code 2 Problem statement: Implement code to process a passenger’s luggage 26 Marius Claassen, Build 3 JavaFX Apps
  • 27. Lecture 5: Airline App – Code 2 package javafx; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; 27 Marius Claassen, Build 3 JavaFX Apps
  • 28. public class AirlineApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("AirlineView.fxml")); primaryStage.setTitle("JavaFX Airline App"); primaryStage.setScene(new Scene(root)); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 28 Marius Claassen, Build 3 JavaFX Apps
  • 29. Lecture 5: Airline App – Code 2 package javafx; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import java.net.URL; import java.time.LocalTime; import java.util.ResourceBundle; 29 Marius Claassen, Build 3 JavaFX Apps
  • 30. public class AirlineController implements Initializable { private static final double EXCESS_RATE_PER_KG = 5.00; @FXML private TextField textFieldLuggageWeight; @FXML private ListView<String> listViewAirlines; @FXML private TextArea textAreaLuggage; @FXML private Button buttonLuggage; 30 Marius Claassen, Build 3 JavaFX Apps
  • 31. @Override public void initialize(URL location, ResourceBundle rb) { listViewAirlines.setItems(FXCollections.observableArrayList( "AA#23kg", "DL#32kg", "AI#25kg", "LO#32kg", "TG#50kg", "PK#30kg")); } 31 Marius Claassen, Build 3 JavaFX Apps
  • 32. @FXML private void luggageButtonClick() { double luggageWeight = Double.parseDouble(textFieldLuggageWeight.getText()); String airline = listViewAirlines.getSelectionModel().getSelectedItem(); String str = airline.substring(3,5); double maxWeight = Double.parseDouble(str); double excessWeight = luggageWeight - maxWeight; double costOfLuggage = excessWeight*EXCESS_RATE_PER_KG; 32 Marius Claassen, Build 3 JavaFX Apps
  • 33. if (excessWeight <= 0) { excessWeight = 0; costOfLuggage = 0; } String luggageCost = "Excess weight: " .concat(String.format("%.2f kgn", excessWeight)) .concat("Cost: $ ") .concat(String.format("%.2f", costOfLuggage)); buttonLuggage.setOnAction(e -> textAreaLuggage.setText(luggageCost)); } } 33 Marius Claassen, Build 3 JavaFX Apps
  • 36. Lecture 6: Airline App – Code 3 Problem statement: Implement code to process the airline meals 36 Marius Claassen, Build 3 JavaFX Apps
  • 37. Lecture 6: Airline App – Code 3 package javafx; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; 37 Marius Claassen, Build 3 JavaFX Apps
  • 38. public class AirlineApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("AirlineView.fxml")); primaryStage.setTitle("JavaFX Airline App"); primaryStage.setScene(new Scene(root)); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 38 Marius Claassen, Build 3 JavaFX Apps
  • 39. Lecture 6: Airline App – Code 3 package javafx; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import java.net.URL; import java.time.LocalTime; import java.util.ResourceBundle; 39 Marius Claassen, Build 3 JavaFX Apps
  • 40. public class AirlineController implements Initializable { @FXML private TextField textFieldNumPassengers; @FXML private TextArea textAreaMeals; @FXML private Button buttonMeals; 40 Marius Claassen, Build 3 JavaFX Apps
  • 41. @FXML private void mealsButtonClick() { int totalMeals = Integer.parseInt(textFieldNumPassengers.getText()); double vegetarianMeals = totalMeals / 3; double nonVegetarianMeals = totalMeals - vegetarianMeals; String mealDistribution = "Vegetarian: " .concat(String.format("%.0fn", vegetarianMeals)) .concat("Non-vegetarian: ") .concat(String.format("%.0f", nonVegetarianMeals)); buttonMeals.setOnAction(e -> textAreaMeals.setText(mealDistribution)); } } 41 Marius Claassen, Build 3 JavaFX Apps
  • 44. Lecture 7: Airline App – Code 4 Problem statement: Implement code to process departure and boarding times 44 Marius Claassen, Build 3 JavaFX Apps
  • 45. Lecture 7: Airline App – Code 4 package javafx; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; 45 Marius Claassen, Build 3 JavaFX Apps
  • 46. public class AirlineApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("AirlineView.fxml")); primaryStage.setTitle("JavaFX Airline App"); primaryStage.setScene(new Scene(root)); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 46 Marius Claassen, Build 3 JavaFX Apps
  • 47. Lecture 7: Airline App – Code 4 package javafx; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import java.net.URL; import java.time.LocalTime; import java.util.ResourceBundle; 47 Marius Claassen, Build 3 JavaFX Apps
  • 48. public class AirlineController implements Initializable { @FXML private TextField textFieldDepartureTime; @FXML private Label labelBoardingTime; @FXML private Button buttonDeparture; 48 Marius Claassen, Build 3 JavaFX Apps
  • 49. @FXML private void departureButtonClick() { buttonDeparture.setOnAction(e -> { if (departureTimeValidated()) { String depart = textFieldDepartureTime.getText(); LocalTime departureTime = LocalTime.parse(depart); LocalTime boardingTime = departureTime.minusMinutes(45); labelBoardingTime.setText(boardingTime.toString()); } }); } 49 Marius Claassen, Build 3 JavaFX Apps
  • 50. private boolean departureTimeValidated() { if (textFieldDepartureTime.getText().isEmpty()) { Alert alert = new Alert(Alert.AlertType.ERROR, "Enter departure time"); alert.setTitle(""); alert.setHeaderText(""); alert.showAndWait(); return false; } return true; } } 50 Marius Claassen, Build 3 JavaFX Apps
  • 55. Lecture 8: Airline App – Code 5 Problem statement: Implement code to process frequent flyer points earned 55 Marius Claassen, Build 3 JavaFX Apps
  • 56. Lecture 8: Airline App – Code 5 package javafx; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; 56 Marius Claassen, Build 3 JavaFX Apps
  • 57. public class AirlineApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("AirlineView.fxml")); primaryStage.setTitle("JavaFX Airline App"); primaryStage.setScene(new Scene(root)); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 57 Marius Claassen, Build 3 JavaFX Apps
  • 58. Lecture 8: Airline App – Code 5 package javafx; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import java.net.URL; import java.time.LocalTime; import java.util.ResourceBundle; 58 Marius Claassen, Build 3 JavaFX Apps
  • 59. public class AirlineController implements Initializable { private ToggleGroup toggleGroup = new ToggleGroup(); 59 Marius Claassen, Build 3 JavaFX Apps
  • 60. @FXML private TextField textFieldKmsTraveled; @FXML private RadioButton radioBtnSilver; @FXML private RadioButton radioBtnGold; @FXML private RadioButton radioBtnPlatinum; @FXML private ImageView imageViewFlyerBenefits; @FXML private Label labelPointsEarned; @FXML private Button buttonFlyerFrequency; 60 Marius Claassen, Build 3 JavaFX Apps
  • 61. @Override public void initialize(URL location, ResourceBundle rb) { private Image image = new Image("file:C:/Users/mariuscn/ IdeaProjects /airlineapp/src/javafx/" + "images/NonMember.jpg"); 61 Marius Claassen, Build 3 JavaFX Apps
  • 63. @FXML public void frequentFlyerButtonClick() { String kmsTraveled = textFieldKmsTraveled.getText(); double kms = Double.parseDouble(kmsTraveled); 63 Marius Claassen, Build 3 JavaFX Apps
  • 64. if (toggleGroup.getSelectedToggle().equals(radioBtnSilver)) { imageViewFlyerBenefits.setImage(new Image( "file:C:/Users/mariuscn/IdeaProjects/airlineapp/src/javafx/images/Silver.jpg")); kms = Math.floor(kms / 1.6); } else if (toggleGroup.getSelectedToggle().equals(radioBtnGold)) { imageViewFlyerBenefits.setImage(new Image( "file:C:/Users/mariuscn/IdeaProjects/airlineapp/src/javafx/images/Gold.jpg")); kms = kms * 0.15 + (Math.floor(kms / 1.6)); } 64 Marius Claassen, Build 3 JavaFX Apps
  • 65. else { imageViewFlyerBenefits.setImage(new Image( "file:C:/Users/mariuscn/IdeaProjects/airlineapp/src/javafx /images/Platinum.jpg")); kms = kms * 0.20 + (Math.floor(kms / 1.6)); } String pointsEarned = "Points earned: " .concat(String.format("%.0f", kms)); buttonFlyerFrequency.setOnAction(e -> labelPointsEarned.setText(pointsEarned)); } } 65 Marius Claassen, Build 3 JavaFX Apps
  • 68. Major components  Introduction  Airline App • Health Centre App • Real Estate App • Conclusion 68 Marius Claassen, Build 3 JavaFX Apps
  • 69. Lecture 9: Health centre - Design Problem statement: Design the graphical user interface of a Health Centre App 69 Marius Claassen, Build 3 JavaFX Apps
  • 71. Lecture 10: Health centre - Style Problem statement: Add style to the design of the Health Centre App 71 Marius Claassen, Build 3 JavaFX Apps
  • 72. Lecture 10: Health centre - Style .mainContainer { -fx-background-color: linear-gradient(violet, pink, violet); } .labelPrimary { -fx-font-family: "Century Gothic"; -fx-font-size: 20; -fx-font-weight: bold; } 72 Marius Claassen, Build 3 JavaFX Apps
  • 73. .labelsSecondary { -fx-font-family: "Century Gothic"; -fx-font-size: 12; -fx-font-weight: bold; } 73 Marius Claassen, Build 3 JavaFX Apps
  • 74. .buttons { -fx-background-color: purple; -fx-background-radius: 50; -fx-font-family: "Century Gothic"; -fx-font-size: 13; -fx-text-fill: white; -fx-font-weight: bold; } 74 Marius Claassen, Build 3 JavaFX Apps
  • 75. .labelsOutput { -fx-background-color: white; -fx-font-family: "Century Gothic"; -fx-font-size: 13; -fx-text-fill: black; -fx-font-weight: bold; } 75 Marius Claassen, Build 3 JavaFX Apps
  • 77. Lecture 11: Health centre – Code 1 Problem statement: Implement code to calculate the amount payable to a health plan 77 Marius Claassen, Build 3 JavaFX Apps
  • 78. Lecture 11: Health centre – Code 1 package javafx; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; 78 Marius Claassen, Build 3 JavaFX Apps
  • 79. public class HealthCentreApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource(“HealthCentreView.fxml")); primaryStage.setTitle("JavaFX Health Centre App"); primaryStage.setScene(new Scene(root)); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 79 Marius Claassen, Build 3 JavaFX Apps
  • 80. Lecture 11: Health centre – Code 1 package javafx; import javafx.collections.FXCollections; import javafxcollections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import java.net.URL; import java.time.LocalTime; import java.util.ResourceBundle; 80 Marius Claassen, Build 3 JavaFX Apps
  • 81. public class HealthCentreController implements Initializable { private static final double Y_CONTRIBUTION_RATE = 70; private static final double C_CONTRIBUTION_RATE = Y_CONTRIBUTION_RATE * 1.1; private static final double L_CONTRIBUTION_RATE = C_CONTRIBUTION_RATE * 1.1; private static final double M_CONTRIBUTION_RATE = L_CONTRIBUTION_RATE * 1.1; 81 Marius Claassen, Build 3 JavaFX Apps
  • 82. @FXML private ListView<String> listViewHealthPlans; @FXML private TextField textFieldDependants; @FXML private Button buttonHealthPlans; 82 Marius Claassen, Build 3 JavaFX Apps
  • 83. @Override public void initialize(URL location, ResourceBundle rb) { textFieldDependants.setText(""); listViewHealthPlans.setItems(FXCollections.observableArrayList( “Option Yud", “Option Chaf", “Option Lamed", “Option Mem")); } 83 Marius Claassen, Build 3 JavaFX Apps
  • 84. @FXML private void healthPlanButtonClick() { buttonHealthPlans.setOnAction(e -> { if (validHealthPlan()) { String plan = listViewHealthPlans.getSelectionModel().getSelectedItem(); int dependants = Integer.parseInt(textFieldDependants.getText()); double = contribution; 84 Marius Claassen, Build 3 JavaFX Apps
  • 85. switch (plan) { case "Option Yud": contribution = Y_CONTRIBUTION_RATE + (dependants * 0.5 * Y_CONTRIBUTION_RATE); break; case "Option Chaf": contribution = C_CONTRIBUTION_RATE + (dependants * 0.5 * C_CONTRIBUTION_RATE); break; case "Option Lamed": contribution = L_CONTRIBUTION_RATE + (dependants * 0.5 * L_CONTRIBUTION_RATE); break; default: contribution = M_CONTRIBUTION_RATE + (dependants * 0.5 * M_CONTRIBUTION_RATE); break; } 85 Marius Claassen, Build 3 JavaFX Apps
  • 86. String result = String.format("%.2f", contribution); Alert alert = new Alert(Alert.AlertType.INFORMATION, "Monthly payment: $" + result); alert.setTitle(""); alert.setHeaderText(""); alert.show(); } }); } 86 Marius Claassen, Build 3 JavaFX Apps
  • 87. private boolean validHealthPlan() { if (textFieldDependants.getText().isEmpty() || (listViewHealthPlans.getSelectionModel().getSelectedItem().isEmpty())) { Alert alert = new Alert(Alert.AlertType.ERROR, "Select health plan and enter number of dependants"); alert.setTitle(""); alert.setHeaderText(""); alert.showAndWait(); return false; } return true; } } 87 Marius Claassen, Build 3 JavaFX Apps
  • 91. Lecture 12: Health centre – Code 2 Problem statement: Implement code to process a payment schedule for 12 months 91 Marius Claassen, Build 3 JavaFX Apps
  • 92. Lecture 12: Health centre – Code 2 package javafx; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; 92 Marius Claassen, Build 3 JavaFX Apps
  • 93. public class HealthCentreApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource(“HealthCentreView.fxml")); primaryStage.setTitle("JavaFX Health Centre App"); primaryStage.setScene(new Scene(root)); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 93 Marius Claassen, Build 3 JavaFX Apps
  • 94. Lecture 12: Health centre – Code 2 package javafx; import javafx.collections.FXCollections; import javafxcollections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import java.net.URL; import java.time.LocalTime; import java.util.ResourceBundle; 94 Marius Claassen, Build 3 JavaFX Apps
  • 95. public class HealthCentreController implements Initializable { private int paymentNo; @FXML private TextField textFieldBalance; @FXML private TableView<Payment> tableViewPmtSchedule; @FXML private TableColumn<Payment, Integer> tableColumnNumber; @FXML private TableColumn<Payment, Integer> tableColumnPayment; @FXML private TableColumn<Payment, Integer> tableColumnBalance; @FXML private Button buttonPayment; 95 Marius Claassen, Build 3 JavaFX Apps
  • 96. @Override public void initialize(URL location, ResourceBundle rb) { textFieldBalance.setText(""); } 96 Marius Claassen, Build 3 JavaFX Apps
  • 97. @FXML private void paymentButtonClick() { int totalOwed = Integer.parseInt(textFieldBalance.getText()); int payment1 = Math.incrementExact((int) (totalOwed *.15)); int balance1 = Math.decrementExact(totalOwed - payment1); int amtPerMonth = Math.round(balance1 / 11); int balance2 = Math.round(balance1 - amtPerMonth); 97 Marius Claassen, Build 3 JavaFX Apps
  • 98. tableColumnNumber.setCellValueFactory(new PropertyValueFactory<>("paymentNumber")); tableColumnPayment.setCellValueFactory(new PropertyValueFactory<>("monthlyPayment")); tableColumnBalance.setCellValueFactory(new PropertyValueFactory<>("amountOwed")); buttonPayment.setOnAction(e -> { paymentNo = 0; final ObservableList<Payment> data = FXCollections.observableArrayList( new Payment(++paymentNo, payment1, balance1), new Payment(++paymentNo, amtPerMonth, balance2), new Payment(++paymentNo, amtPerMonth, balance2-amtPerMonth), new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*2)), new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*3)), 98 Marius Claassen, Build 3 JavaFX Apps
  • 99. new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*4)), new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*5)), new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*6)), new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*7)), new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*8)), new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*9)), new Payment(++paymentNo, amtPerMonth, balance2-(amtPerMonth*10)) ); tableViewPmtSchedule.setItems(data); }); } } 99 Marius Claassen, Build 3 JavaFX Apps
  • 100. package javafx; import javafx.beans.property.SimpleIntegerProperty; public class Payment { private SimpleIntegerProperty paymentNumber; private final SimpleIntegerProperty monthlyPayment; private final SimpleIntegerProperty amountOwed; 100 Marius Claassen, Build 3 JavaFX Apps
  • 101. public Payment(int paymentNo, int monthlyPayment, int amountOwed) { this.paymentNumber = new SimpleIntegerProperty(paymentNo); this.monthlyPayment = new SimpleIntegerProperty(monthlyPayment); this.amountOwed = new SimpleIntegerProperty(amountOwed); } 101 Marius Claassen, Build 3 JavaFX Apps
  • 102. public int getPaymentNumber() { return paymentNumber.get(); } public SimpleIntegerProperty paymentNumberProperty() { return paymentNumber; } public void setPaymentNumber(int paymentNumber) { this.paymentNumber.set(paymentNumber); } 102 Marius Claassen, Build 3 JavaFX Apps
  • 103. public int getMonthlyPayment() { return monthlyPayment.get(); } public SimpleIntegerProperty monthlyPaymentProperty() { return monthlyPayment; } public void setMonthlyPayment(int monthlyPayment) { this.monthlyPayment.set(monthlyPayment); } 103 Marius Claassen, Build 3 JavaFX Apps
  • 104. public int getAmountOwed() { return amountOwed.get(); } public SimpleIntegerProperty amountOwedProperty() { return amountOwed; } public void setAmountOwed(int amountOwed) { this.amountOwed.set(amountOwed); } } 104 Marius Claassen, Build 3 JavaFX Apps
  • 106. Lecture 13: Health centre – Code 3 Problem statement: Implement code to allocate patients to each doctor 106 Marius Claassen, Build 3 JavaFX Apps
  • 107. Lecture 13: Health centre – Code 3 package javafx; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; 107 Marius Claassen, Build 3 JavaFX Apps
  • 108. public class HealthCentreApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource(“HealthCentreView.fxml")); primaryStage.setTitle("JavaFX Health Centre App"); primaryStage.setScene(new Scene(root)); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 108 Marius Claassen, Build 3 JavaFX Apps
  • 109. Lecture 13: Health centre – Code 3 package javafx; import javafx.collections.FXCollections; import javafxcollections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import java.net.URL; import java.time.LocalTime; import java.util.ResourceBundle; 109 Marius Claassen, Build 3 JavaFX Apps
  • 110. public class HealthCentreController implements Initializable { @FXML private TextField textFieldNumberOfPatients; @FXML private Label labelDoctorTsade; @FXML private Label labelDoctorKuf; @FXML private Label labelDoctorReish; @FXML private Button buttonDoctor; 110 Marius Claassen, Build 3 JavaFX Apps
  • 111. @Override public void initialize(URL location, ResourceBundle rb) { textFieldNumberOfPatients.setText(""); } 111 Marius Claassen, Build 3 JavaFX Apps
  • 112. @FXML private void doctorButtonClick() { int totalPatients = Integer.parseInt(textFieldNumberOfPatients.getText()); int patientsPerDoctor = totalPatients / 3; int remainder = totalPatients % 3; int doctorTsade = patientsPerDoctor; int doctorKuf = patientsPerDoctor; 112 Marius Claassen, Build 3 JavaFX Apps
  • 113. if (remainder == 2) { doctorTsade++; doctorKuf++; } else { doctorTsade++; } 113 Marius Claassen, Build 3 JavaFX Apps
  • 114. String patientsDrTsade = String.format(" %d", doctorTsade); String patientsDrKuf = String.format(" %d", doctorKuf); String patientsDrReish = String.format(" %d", patientsPerDoctor); buttonDoctor.setOnAction(e -> { labelDoctorTsade.setText(patientsDrTsade); labelDoctorKuf.setText(patientsDrKuf); labelDoctorReish.setText(patientsDrReish); } ); } } 114 Marius Claassen, Build 3 JavaFX Apps
  • 117. Lecture 14: Health centre – Code 4 Problem statement: Implement code to process the doctors’ hours at work 117 Marius Claassen, Build 3 JavaFX Apps
  • 118. Lecture 14: Health centre – Code 4 package javafx; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; 118 Marius Claassen, Build 3 JavaFX Apps
  • 119. public class HealthCentreApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource(“HealthCentreView.fxml")); primaryStage.setTitle("JavaFX Health Centre App"); primaryStage.setScene(new Scene(root)); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 119 Marius Claassen, Build 3 JavaFX Apps
  • 120. Lecture 14: Health centre – Code 4 package javafx; import javafx.collections.FXCollections; import javafxcollections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import java.net.URL; import java.time.LocalTime; import java.util.ResourceBundle; 120 Marius Claassen, Build 3 JavaFX Apps
  • 121. public class HealthCentreController implements Initializable { private ToggleGroup toggleGroup = new ToggleGroup(); @FXML private TextField textFieldNumberOfPatients; @FXML private Label labelDoctorTsade; @FXML private Label labelDoctorKuf; @FXML private Label labelDoctorReish; @FXML private Button buttonDoctor; 121 Marius Claassen, Build 3 JavaFX Apps
  • 122. @FXML private TextField textFieldNumberOfMinutes; @FXML private RadioButton radioButtonEight; @FXML private RadioButton radioButtonEleven; @FXML private RadioButton radioButtonThirteen; @FXML private Label labelTimeAtWork; @FXML private Label labelSignOutTime; 122 Marius Claassen, Build 3 JavaFX Apps
  • 123. @Override public void initialize(URL location, ResourceBundle rb) { textFieldNumberOfPatients.setText(""); textFieldMinutesPerPatient.setText(""); } 123 Marius Claassen, Build 3 JavaFX Apps
  • 124. @FXML private void doctorButtonClick() { int totalPatients = Integer.parseInt(textFieldNumberOfPatients.getText()); int patientsPerDoctor = totalPatients / 3; int remainder = totalPatients % 3; int doctorTsade = patientsPerDoctor; int doctorKuf = patientsPerDoctor; 124 Marius Claassen, Build 3 JavaFX Apps
  • 125. if (remainder == 2) { doctorTsade++; doctorKuf++; } else { doctorTsade++; } 125 Marius Claassen, Build 3 JavaFX Apps
  • 126. int hours = 0; int minutes; int aveConsultationTime = Integer.parseInt(textFieldNumberOfMinutes.getText()); int totalConsultationTime = doctorTsade * aveConsultationTime; int hoursWorked = 0; 126 Marius Claassen, Build 3 JavaFX Apps
  • 127. if (totalConsultationTime < 60) { minutes = totalConsultationTime; hoursWorked++; } else if (totalConsultationTime < 120) { hours++; minutes = totalConsultationTime - 60; hoursWorked += 2; } else if (totalConsultationTime < 180) { hours += 2; minutes = totalConsultationTime - 60; hoursWorked += 3; } 127 Marius Claassen, Build 3 JavaFX Apps
  • 128. else if (totalConsultationTime < 240) { hours += 3; minutes = totalConsultationTime - 60; hoursWorked += 4; } else { hours += 4; minutes = totalConsultationTime - 60; hoursWorked += 5; } 128 Marius Claassen, Build 3 JavaFX Apps
  • 129. radioButtonEight.setToggleGroup(toggleGroup); radioButtonEleven.setToggleGroup(toggleGroup); radioButtonThirteen.setToggleGroup(toggleGroup); LocalTime time1 = LocalTime.of(8,0); LocalTime time2 = LocalTime.of(11,0); LocalTime time3 = LocalTime.of(13,0); final LocalTime signOut; 129 Marius Claassen, Build 3 JavaFX Apps
  • 130. if (toggleGroup.getSelectedToggle().equals(radioButtonEight)) { signOut = time1.plusHours(hoursWorked); } else if (toggleGroup.getSelectedToggle().equals(radioButtonEleven)) { signOut = time2.plusHours(hoursWorked); } else { signOut = time3.plusHours(hoursWorked); } 130 Marius Claassen, Build 3 JavaFX Apps
  • 131. String patientsDrTsade = String.format(" %d", doctorTsade); String patientsDrKuf = String.format(" %d", doctorKuf); String patientsDrReish = String.format(" %d", patientsPerDoctor); String timeAtWork = " " .concat(String.format("%d", hours)) .concat(" hour(s)") .concat(String.format(" %d", minutes)) .concat(" minutes"); 131 Marius Claassen, Build 3 JavaFX Apps
  • 135. Major components  Introduction  Airline App  Health Centre App • Real Estate App • Conclusion 135 Marius Claassen, Build 3 JavaFX Apps
  • 136. Lecture 15: Real estate - Design Problem statement: Design the graphical user interface of a Real Estate App 136 Marius Claassen, Build 3 JavaFX Apps
  • 140. Lecture 16: Real estate App - Style Problem statement: Add style to the design of the Real Estate App 140 Marius Claassen, Build 3 JavaFX Apps
  • 141. Lecture 16: Real estate App - Style .mainContainer { -fx-background-color: linear-gradient(gold, lemochiffon, gold); } .labelsPrimary { -fx-font-family: "Century Gothic"; -fx-font-size: 17; -fx-font-weight: bold; } 141 Marius Claassen, Build 3 JavaFX Apps
  • 142. .labelsSecondary, .checkBox, .radioButtons { -fx-font-family: "Century Gothic"; -fx-font-size: 16; } 142 Marius Claassen, Build 3 JavaFX Apps
  • 143. .labelOutput { -fx-background-color: white; -fx-font-family: "Century Gothic"; -fx-font-size: 13; -fx-text-fill: black; -fx-font-weight: bold; } 143 Marius Claassen, Build 3 JavaFX Apps
  • 144. .buttons { -fx-background-color: orange; -fx-background-radius: 50; -fx-font-family: "Century Gothic"; -fx-font-size: 16; -fx-text-fill: black; -fx-font-weight: bold; } 144 Marius Claassen, Build 3 JavaFX Apps
  • 148. Lecture 17: Real estate – Code 1 Problem statement: Implement code to generate an advertisement 148 Marius Claassen, Build 3 JavaFX Apps
  • 149. Lecture 17: Real estate – Code 1 package javafx; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; 149 Marius Claassen, Build 3 JavaFX Apps
  • 150. public class RealEstateApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource(“RealEstateViews.fxml")); primaryStage.setTitle("JavaFX Real Estate App"); primaryStage.setScene(new Scene(root)); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 150 Marius Claassen, Build 3 JavaFX Apps
  • 151. Lecture 17: Real estate – Code 1 package javafx; import javafx.beans.binding.StringBinding; import javafx.beans.binding.StringExpression; import javafx.beans.binding.When; import javafx.beans.property.*; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.fxml.FXML; import javafx.scene.control.*; import java.util.Optional; 151 Marius Claassen, Build 3 JavaFX Apps
  • 152. public class RealEstateController { @FXML private TextField textFieldMarketValue; @FXML private TextField textFieldSellingPrice; @FXML private TextField textFieldNumberOfBedrooms; @FXML private TextField textFieldNumberOfBathrooms; @FXML private CheckBox checkBoxSwimmingPool; @FXML private Button buttonAdvertisement; @FXML private TextArea textAreaAdvertisement; 152 Marius Claassen, Build 3 JavaFX Apps
  • 153. @FXML public void advertisementButtonClick() { StringProperty advert = new SimpleStringProperty("nHOUSE FOR SALE:"); StringBinding swimmingPool = new When (checkBoxSwimmingPool.selectedProperty()) .then("Swimming Pool") .otherwise(""); 153 Marius Claassen, Build 3 JavaFX Apps
  • 154. int marketValue = Integer.parseInt(textFieldMarketValue.getText()); int sellingPrice = Integer.parseInt(textFieldSellingPrice.getText()); int numberOfBedrooms = Integer.parseInt(textFieldNumberOfBedrooms.getText()); int numberOfBathrooms = Integer.parseInt(textFieldNumberOfBathrooms.getText()); String bargain = (sellingPrice < marketValue) ? "Bargain" : ""; 154 Marius Claassen, Build 3 JavaFX Apps
  • 155. StringExpression advertisementDetails = advert .concat("nSelling Price: $") .concat(String.format("%d",sellingPrice)) .concat("nBedrooms: ") .concat(String.format("%d", numberOfBedrooms)) .concat("nBathrooms: ") .concat(String.format("%d", numberOfBathrooms)) .concat("n") .concat(swimmingPool) .concat("n") .concat(bargain); 155 Marius Claassen, Build 3 JavaFX Apps
  • 160. Lecture 18: Real estate – Code 2 Problem statement: Implement code to process renovations to the living room 160 Marius Claassen, Build 3 JavaFX Apps
  • 161. Lecture 18: Real estate – Code 2 package javafx; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; 161 Marius Claassen, Build 3 JavaFX Apps
  • 162. public class RealEstateApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource(“RealEstateViews.fxml")); primaryStage.setTitle("JavaFX Real Estate App"); primaryStage.setScene(new Scene(root)); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 162 Marius Claassen, Build 3 JavaFX Apps
  • 163. Lecture 18: Real estate – Code 2 package javafx; import javafx.beans.binding.StringBinding; import javafx.beans.binding.StringExpression; import javafx.beans.binding.When; import javafx.beans.property.*; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.fxml.FXML; import javafx.scene.control.*; import java.util.Optional; 163 Marius Claassen, Build 3 JavaFX Apps
  • 164. public class RealEstateController { private static final double AREA_PER_LTR_PAINT = 8; private static final double FIVE_LTR_COST = 18.70; private static final double TWO_LTR_COST = 9.60; private static final double ONE_LTR_COST = 5.45; private static final int FIVE_LTR_DRUM = 5; private static final int TWO_LTR_DRUM = 2; private static final double TILE_BREAKAGES = 5; 164 Marius Claassen, Build 3 JavaFX Apps
  • 165. @FXML private TextField textFieldAreaToRenovate; @FXML private RadioButton radioButtonPainting; @FXML private RadioButton radioButtonTiling; @FXML private Button buttonRenovationsCost; @FXML private TextArea textAreaRenovationsCost; 165 Marius Claassen, Build 3 JavaFX Apps
  • 166. @FXML private void renovationsButtonClick() { ToggleGroup toggleGroup = new ToggleGroup(); radioButtonPainting.setToggleGroup(toggleGroup); radioButtonTiling.setToggleGroup(toggleGroup); double areaToRenovate = Double.parseDouble(textFieldAreaToRenovate.getText()); double volumeOfPaint = areaToRenovate / AREA_PER_LTR_PAINT; 166 Marius Claassen, Build 3 JavaFX Apps
  • 167. int numberOfFiveLtrDrums = (int) volumeOfPaint / FIVE_LTR_DRUM; int numberOfTwoLtrDrums = (int) Math.round((volumeOfPaint - (numberOfFiveLtrDrums * FIVE_LTR_DRUM))) / 2; int numberOfOneLtrDrums = (int) Math.round(volumeOfPaint - (numberOfFiveLtrDrums * FIVE_LTR_DRUM) - (numberOfTwoLtrDrums * TWO_LTR_DRUM)); 167 Marius Claassen, Build 3 JavaFX Apps
  • 168. double costOfPaint = (numberOfFiveLtrDrums * FIVE_LTR_COST) + (numberOfTwoLtrDrums * TWO_LTR_COST) + (numberOfOneLtrDrums * ONE_LTR_COST); double tileCostPerSqMetre = 0; double costOfTiles; 168 Marius Claassen, Build 3 JavaFX Apps
  • 169. if (toggleGroup.getSelectedToggle().equals(radioButtonPainting )) { String paintingDetails = "nAREA TO PAINT:" .concat(String.format("n%.0f", areaToRenovate)) .concat(" square metres") .concat("nnVolume of paint required: ") .concat(String.format("%.1f", volumeOfPaint)) .concat(" litres") 169 Marius Claassen, Build 3 JavaFX Apps
  • 170. .concat("n1-litre drums: ") .concat(String.format("%d", numberOfOneLtrDrums)) .concat("n2-litre drums: ") .concat(String.format("%d", numberOfTwoLtrDrums)) .concat("n5-litre drums: ") .concat(String.format("%d", numberOfFiveLtrDrums)) .concat("nnTotal cost: $") .concat(String.format("%.2f", costOfPaint)); 170 Marius Claassen, Build 3 JavaFX Apps
  • 172. } else { TextInputDialog input = new TextInputDialog(); input.setTitle(""); input.setHeaderText(""); input.setContentText("Enter tiling cost per square metre"); input.showAndWait() .ifPresent(str -> tileCostPerSqMetre[0] = Double.parseDouble(str)); 172 Marius Claassen, Build 3 JavaFX Apps
  • 173. costOfTiles = (areaToRenovate + TILE_BREAKAGES) * tileCostPerSqMetre[0]; String tilingDetails = "nAREA TO TILE:" .concat(String.format("n%.0f", areaToRenovate)) .concat(" square metres") .concat("nTotal cost: $") .concat(String.format("%.2f",costOfTiles)); buttonRenovationsCost.setOnAction(e -> textAreaRenovationsCost.setText(tilingDetails)); } } } 173 Marius Claassen, Build 3 JavaFX Apps
  • 177. Lecture 19: Real estate – Code 3 Problem statement: Implement code to calculate the electricity amount payable 177 Marius Claassen, Build 3 JavaFX Apps
  • 178. Lecture 19: Real estate – Code 3 package javafx; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; 178 Marius Claassen, Build 3 JavaFX Apps
  • 179. public class RealEstateApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource(“RealEstateViews.fxml")); primaryStage.setTitle("JavaFX Real Estate App"); primaryStage.setScene(new Scene(root)); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 179 Marius Claassen, Build 3 JavaFX Apps
  • 180. Lecture 19: Real estate – Code 3 package javafx; import javafx.beans.binding.StringBinding; import javafx.beans.binding.StringExpression; import javafx.beans.binding.When; import javafx.beans.property.*; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.fxml.FXML; import javafx.scene.control.*; import java.util.Optional; 180 Marius Claassen, Build 3 JavaFX Apps
  • 181. public class RealEstateController { private static final int ELECTRICITY_LOWER_LIMIT_UNITS = 600; private static final int ELECTRICITY_LOWER_LIMIT_AMOUNT = 50; private static final double ELECTRICITY_LOWER_TARIFF = 0.10; private static final double ELECTRICITY_UPPER_TARIFF = 0.15; 181 Marius Claassen, Build 3 JavaFX Apps
  • 182. @FXML private TextField textFieldPreviousReading; @FXML private TextField textFieldCurrentReading; @FXML private Label labelElectricity; @FXML private Button buttonElectricityAmount; 182 Marius Claassen, Build 3 JavaFX Apps
  • 183. @FXML private void electricityButtonClick() { int previousReading = Integer.parseInt(textFieldPreviousReading.getText()); int currentReading = Integer.parseInt(textFieldCurrentReading.getText()); double amountDue; 183 Marius Claassen, Build 3 JavaFX Apps
  • 184. if (currentReading <= previousReading) { Alert alert = new Alert(Alert.AlertType.ERROR, "Enter current reading greater than previous reading"); alert.setTitle(""); alert.setHeaderText(""); alert.showAndWait(); textFieldCurrentReading.setText(""); 184 Marius Claassen, Build 3 JavaFX Apps
  • 185. } else { if ((currentReading - previousReading) <= ELECTRICITY_LOWER_LIMIT_UNITS) { amountDue = (currentReading - previousReading) * ELECTRICITY_LOWER_TARIFF; } else { amountDue = (ELECTRICITY_LOWER_LIMIT_AMOUNT + (currentReading - (previousReading + ELECTRICITY_LOWER_LIMIT_UNITS)) * ELECTRICITY_UPPER_TARIFF); } String amount = " $".concat(String.format("%.2f", amountDue)); buttonElectricityAmount.setOnAction(e -> labelElectricity.setText(amount)); } } } 185 Marius Claassen, Build 3 JavaFX Apps
  • 189. Lecture 20: Real estate – Code 4 Problem statement: Implement code to display the size of geyser matching the user input 189 Marius Claassen, Build 3 JavaFX Apps
  • 190. Lecture 20: Real estate – Code 4 package javafx; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; 190 Marius Claassen, Build 3 JavaFX Apps
  • 191. public class RealEstateApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource(“RealEstateViews.fxml")); primaryStage.setTitle("JavaFX Real Estate App"); primaryStage.setScene(new Scene(root)); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 191 Marius Claassen, Build 3 JavaFX Apps
  • 192. Lecture 20: Real estate – Code 4 package javafx; import javafx.beans.binding.StringBinding; import javafx.beans.binding.StringExpression; import javafx.beans.binding.When; import javafx.beans.property.*; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.fxml.FXML; import javafx.scene.control.*; import java.util.Optional; 192 Marius Claassen, Build 3 JavaFX Apps
  • 193. public class RealEstateController { private static final ObservableList<String> solarGeysers = FXCollections.observableArrayList( "50-BetSolar", "50-GimmelWonder", "50-DaletSun", "100-BetSolar", "100-GimmelWonder", "100-DaletSun", "150-BetSolar", "150-GimmelWonder", "150-DaletSun"); 193 Marius Claassen, Build 3 JavaFX Apps
  • 194. @FXML private TextField textFieldGeyser; @FXML private TextArea textAreaGeyser; @FXML private Button buttonGeyser; 194 Marius Claassen, Build 3 JavaFX Apps
  • 195. @FXML private void geyserButtonClick() { int geyserSize = Integer.parseInt(textFieldGeyser.getText()); FilteredList<String> geyserList; 195 Marius Claassen, Build 3 JavaFX Apps
  • 196. if (geyserSize == 50) { geyserList = solarGeysers.filtered(g -> g.startsWith("50")); } else if (geyserSize == 100) { geyserList = solarGeysers.filtered(g -> g.startsWith("100")); } else { geyserList = solarGeysers.filtered(g -> g.startsWith("150")); } 196 Marius Claassen, Build 3 JavaFX Apps
  • 197. FilteredList<String> finalGeyserList = geyserList; buttonGeyser.setOnAction(e -> textAreaGeyser.setText( String.format("%s", finalGeyserList))); } } 197 Marius Claassen, Build 3 JavaFX Apps
  • 200. To access this course: • https://www.udemy.com/course/1474854/manage/basics/ or • mariusclaassen@gmail.com 200 Marius Claassen, Build 3 JavaFX Apps
  • 201. Build 3 JavaFX Apps Real-world, modern-looking GUIs with JavaFX Marius Claassen, Build 3 JavaFX Apps