0% found this document useful (0 votes)
171 views12 pages

Chapter 1 - Javafx - Introduction

This document introduces JavaFX and provides examples of basic JavaFX programs. It discusses that JavaFX is a Java technology for building desktop graphical user interfaces (GUIs). It provides visual components like labels, buttons, text fields etc. that can be used to display outputs, receive inputs from users and present instructions. The document then gives examples of simple JavaFX programs - a basic "Hello World" program, customizing styles of labels and containers, handling button click events, and a program with a counting label and button. It demonstrates key concepts like defining a JavaFX Application class, using stages and scenes to display windows, and event-driven programming with listeners.

Uploaded by

Hunter
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
171 views12 pages

Chapter 1 - Javafx - Introduction

This document introduces JavaFX and provides examples of basic JavaFX programs. It discusses that JavaFX is a Java technology for building desktop graphical user interfaces (GUIs). It provides visual components like labels, buttons, text fields etc. that can be used to display outputs, receive inputs from users and present instructions. The document then gives examples of simple JavaFX programs - a basic "Hello World" program, customizing styles of labels and containers, handling button click events, and a program with a counting label and button. It demonstrates key concepts like defining a JavaFX Application class, using stages and scenes to display windows, and event-driven programming with listeners.

Uploaded by

Hunter
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

Chapter 1 – JavaFX – Introduction

1 Introduction

1.1 What is JavaFX?

• JavaFX is a Java technology that allows us to build desktop graphical user interfaces
(GUI’s).

• The user interface of an application is what the application presents to the user to allow
the user to interact with it
Through the user interface, the program receives inputs from the user and presents
outputs to the user
A graphical user interface is one that uses visual components. More specifically, it uses
visual components to

– To display instructions to the user,


– To receive inputs from the user, and
– To present outputs to the user

• Java provides two technologies for GUI desktop applications: Swing and JavaFX. The
concepts used in the two approaches are on the whole quite similar to each other.
We will use JavaFX. Swing is the older technology. It will not be further developed.
JavaFX is the newer technology. It offers a richer set of features. It is more cleanly
designed. And it is easier to use.

• JavaFX is in fact a Java class library, i.e. a collection of classes and interfaces.

• JavaFX is supported by Java 8, the version we use for this subject.


Various features of Java 8, in particular lambda expressions, will be introduced as the
needs arise.

An Exercise for Thought:

Consider two programs. One is a typical program that presents a command-line interface
for the user to add two numbers. The other program presents a graphical user interface
to allow the user to perform the same operation. Drawing on your experience, identify
the differences between them.

1
1.2 Key Concepts for JavaFX Programming

• From the programming point of view, we can think of JavaFX approach as being based
on two main ideas.

• First, JavaFX provides a comprehensive collection of classes to represent visual


elements. The visual elements can be divided into two main categories: GUI controls
and containers.
GUI controls are visual elements to provide the user with information and means of
interaction. Some of the most commonly used GUI controls are:

– Label
– Button
– TextField
– CheckBox
– RadioButton
– TextArea
– ChoiceBox
– Table
– Menu

Containers are visual components that can contain GUI controls and other containers.
Some of the most commonly used containers are

– FlowPane
– BorderPane
– VBox
– HBox

– Scene
– Stage

• Second, the execution of the GUI application is event-driven


That is, when the program is running, various kinds of events - mostly as a result of the
user’s actions - are generated
Events, once generated, are then handled by the event handlers
Some of the most commonly used listeners are:

– ActionEvent
– KeyEvent
– MouseEvent
– WindowEvent

• In this chapter, we will introduce the basic elements of a JavaFX application through a
few simple examples.

2
2 HelloWorld 1 – Basic

We now illustrate these basic concepts with a very simple program: our first Hello World
program.

1 public class HelloWorld1 extends Application


2 {
3 public static void main(String [] args)
4 {
5 Application.launch();
6 }
7
8 public void start(Stage stage)
9 {
10 // D e f i n e a l a b e l
11 Label label = new Label("Hello World!");
12
13 // Place the l a b e l i n a vbox c o n t a i n e r
14 VBox root = new VBox(label);
15
16 // D e f i n e the s c e n e
17 Scene scene = new Scene(root);
18
19 // Set the s c e n e f o r the s t a g e and show i t
20 stage.setScene(scene);
21 stage.setTitle(getClass().getName());
22 stage.show();
23 }
24 }

Compile and run the program (with Java 8), we get:

As can be seen in the program above,

• A JavaFX application is a class that extends the javafx.application.Application


class.

• When we run a JavaFX application, the JVM executes the main method. Then,
– The main method calls the launch method.
– The launch method calls the start method.
– The start method displays a stage.

• A stage is a top-level container. It is displayed as a window on the screen.


A stage must have a scene.
A scene typically contains other container objects (e.g. a VBox), which contain GUI
controls (labels, buttons, etc.)

• Essentially, to define an FX application, we define (override) the start method.

3
3 HelloWorld 2 – With Customized Style Properties

Let us make it look a little nicer by specifying a few style properties for the label and the
root. We also set the initial size of the Scene to 600x300.

1 import javafx.application.Application;
2 import javafx.stage.Stage;
3 import javafx.scene.Scene;
4 import javafx.scene.control.Label;
5 import javafx.scene.layout.VBox;
6
7 public class HelloWorld2 extends Application
8 {
9 public static void main(String [] args)
10 {
11 Application.launch();
12 }
13
14 public void start(Stage stage)
15 {
16 // D e f i n e a l a b e l
17 Label label = new Label("Hello World!");
18
19 // Place l a b e l i n a vbox
20 VBox root = new VBox(label);
21
22 // Set s c e n e
23 Scene scene = new Scene(root, 600, 300);
24
25 // Set s t a g e
26 stage.setScene(scene);
27 stage.setTitle(getClass().getName());
28 stage.show();
29
30 // Set some s t y l e p r o p e r t i e s f o r l a b e l and vbox
31 label.setStyle("-fx-font-size: 100; -fx-text-fill: blue;");
32 root.setStyle("-fx-alignment: center;");
33 }
34 }

As shown in the program,

• we can set various style properties of a control or container by using JavaFX CSS styles
• The JavaFX style properties and associated values are borrowed from the well-known
CSS style for web pages.

For a good source of reference on the Web, which can be put to practical use, see:
https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html

4
4 HelloWorld 3 – Responding to User’s Actions

Next, we will have a Hello World program that responds to the user’s action. This application has
a button and when click on the button, it writes “Hello World!” on the command window.

This is our first example of event handling. When we click on the button, an event is generated,
and this event is responded to in a way that produce the behavior described above.

This example also demonstrates the fact that we can omit the main method. It will be called by
default.

1 import javafx.application.Application;
2 import javafx.stage.Stage;
3 import javafx.scene.Scene;
4 import javafx.scene.control.Button;
5 import javafx.scene.text.Font;
6 import javafx.scene.layout.VBox;
7
8 public class HelloWorld3 extends Application
9 {
10 public void start(Stage stage)
11 {
12 Button button = new Button("Say ’Hello World’");
13
14 button.setOnAction(e ->
15 {
16 System.out.println("Hello World!");
17 });
18
19 VBox root = new VBox(button);
20 Scene scene = new Scene(root, 600, 300);
21
22 stage.setScene(scene);
23 stage.setTitle(getClass().getName());
24 stage.show();
25
26 button.setStyle("-fx-font-size: 50;");
27 root.setStyle("-fx-alignment: center;");
28 }
29 }

What we have from line 14 to line 17 is known as a lambda expression. Lambda expressions will
be covered later. For now, let us read it like this:

When ActionEvent e occurs, execute the following statement(s):


System.out.println("Hello World!");

An Exercise (Something to try):


Change the statement in the lambda expression to the following and run the program:
System.out.println("Hello World!");
System.out.println(e);
((Button) e.getSource()).setText("I have been clicked on!");

5
5 HelloWorld 4 – Enhancing HelloWorld3

Now, we have a program that has two controls: a Label and a Button. The program counts how
many times we press the button and displays the count on the Label.

1 import javafx.application.Application;
2 import javafx.stage.Stage;
3 import javafx.scene.Scene;
4 import javafx.scene.control.Label;
5 import javafx.scene.control.Button;
6 import javafx.scene.text.Font;
7 import javafx.scene.layout.VBox;
8
9 public class HelloWorld4 extends Application
10 {
11 int count = 0;
12
13 public void start(Stage stage)
14 {
15 Label label = new Label("Say-Hello Count: 0");
16
17 Button button = new Button("Say ’Hello World’");
18 button.setOnAction(e ->
19 {
20 count++;
21 label.setText(
22 "Say-Hello Count: " + count);
23 });
24
25 VBox root = new VBox(label, button);
26 Scene scene = new Scene(root, 600, 300);
27
28 stage.setScene(scene);
29 stage.setTitle("Demo");
30 stage.show();
31
32 label.setStyle("-fx-font-size: 25; -fx-text-fill: blue");
33 button.setStyle("-fx-font-size: 30");
34 root.setStyle("-fx-alignment: center; -fx-spacing: 20;");
35 }
36 }

The screenshots at the start of the program and after two clicks on the button are shown below:

6
6 Sample FX Program

In this section, we will present a sample JavaFX program. We can use this prorgam as a starting
point to define a new FX application.

To work toward this sample program, we re-write the previous program in the following form:

HelloWorld 4 Rewritten

1 import javafx.application.Application;
2 import javafx.stage.Stage;
3 import javafx.scene.Scene;
4 import javafx.scene.control.Label;
5 import javafx.scene.control.Button;
6 import javafx.scene.text.Font;
7 import javafx.scene.layout.VBox;
8
9 public class HelloWorld5 extends Application
10 {
11 int count = 0;
12
13 public void start(Stage stage)
14 {
15 build(stage); // b u i l d the c o n t e n t o f the s t a g e
16 stage.setTitle(getClass().getName()); // s e t program ’ s name as a d e f a u l t
17 stage.show();
18 }
19
20 public void build(Stage stage) // put b u i l d t a s k i n t h i s method
21 {
22
23 Label label = new Label("Say-Hello Count: 0");
24
25 Button button = new Button("Say Hello World");
26 button.setOnAction(e ->
27 {
28 count++;
29 label.setText("Say-Hello Count: " + count);
30 });
31
32 VBox root = new VBox(label, button);
33 Scene scene = new Scene(root, 600, 300);
34
35 stage.setScene(scene);
36 stage.setTitle("Demo");
37 stage.show();
38
39 label.setStyle("-fx-font-size: 25; -fx-text-fill: blue");
40 button.setStyle("-fx-font-size: 30");
41 root.setStyle("-fx-alignment: center; -fx-spacing: 20;");
42 }
43 }

Note that the work that is specific to the application is done in the build method.

This leads us to the sample program shown on the next page.

7
Sample FX Program

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.*;

public class SampleFX extends Application


{
public void start(Stage stage)
{
build(stage);
stage.setTitle(getClass().getName());
stage.show();
}

public void build(Stage stage)


{
// D e f i n e c o n t r o l s and l a y o u t
VBox root = new VBox();

// Set s c e n e and s t a g e
Scene scene = new Scene(root, 500, 400);
stage.setScene(scene);
}
}

It is often convenient to start a new application with this sample program and then change it as
required.

8
7 A Closer Look: The Application Class, Life Cycle and
FXThread

To gain a better understanding, let us have a closer look at what happen when a JavaFX application
is launched.

The Life Cycle of a JavaFX Application

The Application class is responsible for managing the life cycle of a JavaFX application. The life
cycle consists of the following steps:

1. Call the init() method.


The default implementation of the init() method does nothing, but you can override this
method to provide any processing you want to be performed before the applications user
interface displays.
2. Create an instance of Stage if there is no main() method or if the main() method calls the
launch() method
3. Call the start() method.
The start method of the Application class is an abstract method. Therefore, we must override
this method, which is responsible for building and displaying the required user interface.
4. Wait for the application to finish, which happens when either of the following occur:

– the last window has been closed, or


– the application calls Platform.exit()

During this time, the application would be performing actions in response to user inputs.
5. Call the stop() method.
This method has a default implementation which does nothing. We can override this method
if we wish.

The start method is abstract and must be overridden. The init and stop methods have concrete
implementations that do nothing.

The above life cycle of JavaFX applications can be illustrated by the program below:

9
1 import javafx.application.Application;
2 import javafx.stage.Stage;
3 import javafx.scene.Scene;
4 import javafx.scene.control.*;
5 import javafx.scene.layout.*;
6
7 public class LifeCycle extends Application
8 {
9 public static void main(String[] args)
10 {
11 Application.launch(args);
12 }
13
14 public void init()
15 {
16 System.out.println(">> init() is called.");
17 }
18
19 public void start(Stage stage)
20 {
21 build(stage);
22 stage.setTitle(getClass().getName());
23 stage.show();
24 }
25
26 private void build(Stage stage)
27 {
28 // D e f i n e c o n t r o l and l a y o u t
29 Button bt = new Button("Click me");
30 bt.setOnAction(e ->
31 {
32 System.out.println("The button is clicked.");
33 });
34
35 VBox root = new VBox(bt);
36
37
38 // D e f i n e the s c e n e and s e t the s t a g e
39 Scene scene = new Scene(root, 400, 300);
40 stage.setScene(scene);
41 }
42
43 public void stop()
44 {
45 System.out.println(">> stop() is called.");
46 }
47 }

10
JavaFX Threads

When a JavaFX application is launched, two particular JavaFX threads are created: the JavaFX
Launcher Application Thread and the JavaFX Application Thread.

• The JavaFX Launcher Thread is the thread that launches the application. The init() method is
called on the JavaFX Launcher Thread.
• The JavaFX Application Thread is the thread that runs the application’s start() and stop()
methods.
In particular, JavaFX Scene and Stage objects can only be created on the JavaFX Application
Thread.

The following program gives a quick demonstration of the JavaFX threads.

1 import javafx.application.Application;
2 import javafx.application.Platform;
3 import javafx.scene.Scene;
4 import javafx.stage.Stage;
5 import javafx.scene.control.Label;
6
7 public class FXThreads extends Application
8 {
9 public static void main(String [] args)
10 {
11 System.out.printf("main() called on thread %s%n",
12 Thread.currentThread());
13
14 Application.launch(args);
15
16 System.out.printf(
17 "Just before the program’s termination, the thread is: %s%n",
18 Thread.currentThread());
19 }
20
21 @Override
22 public void init()
23 {
24 System.out.printf("init() called on thread %s%n",
25 Thread.currentThread());
26 }
27
28 @Override
29 public void start(Stage stage)
30 {
31 System.out.printf("start() called on thread %s%n", Thread.currentThread()
);
32
33 stage.setScene(new Scene(new Label("Hello")));
34 stage.show();
35 }
36
37 @Override
38 public void stop()
39 {
40 System.out.printf("stop() called on thread %s%n", Thread.currentThread())
;
41 }
42 }

11
An Exercise (Something to try):
In the API documentation of class Application, we see and the following remarks about parameters

Parameters
Application parameters are available by calling the getParameters() method from the
init() method, or any time after the init method has been called.

and the method

Application.Parameters getParameters()
Retrieves the parameters for this Application, including any arguments passed on the
command line and any parameters . . .

Modify the previous program to display the command-line parameters, as Strings, on the command-
prompt window.
Do this from the start method. Consult the API documentation if necessary.

12

You might also like