0% found this document useful (0 votes)
2 views49 pages

Java FX Note

JavaFX is a Java library for developing desktop and rich internet applications that can run on multiple platforms. It serves as a replacement for Swing, offering more functionalities and a hierarchical structure consisting of Stage, Scene, and nodes. The document provides a comprehensive guide on creating a basic JavaFX application, including layout management and event handling.

Uploaded by

Sanskriti Poudel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views49 pages

Java FX Note

JavaFX is a Java library for developing desktop and rich internet applications that can run on multiple platforms. It serves as a replacement for Swing, offering more functionalities and a hierarchical structure consisting of Stage, Scene, and nodes. The document provides a comprehensive guide on creating a basic JavaFX application, including layout management and event handling.

Uploaded by

Sanskriti Poudel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What is JavaFX?

JavaFX is a Java library used to develop Desktop applications as well as Rich Internet
Applications (RIA). The applications built in JavaFX, can run on multiple platforms
including Web, Mobile and Desktops.

JavaFX is intended to replace swing in Java applications as a GUI framework. However, It


provides more functionalities than swing. Like Swing, JavaFX also provides its own
components and doesn't depend upon the operating system. It is lightweight and
hardware accelerated. It supports various operating systems including Windows, Linux
and Mac OS.

JavaFX Application Structure


JavaFX application is divided hierarchically into three main components known as Stage,
Scene and nodes. We need to import [Link] class in every
JavaFX application. This provides the following life cycle methods for JavaFX application.

o public void init()


o public abstract void start(Stage primaryStage)
o public void stop()

in order to create a basic JavaFX application, we need to:

1. Import [Link] into our code.


2. Inherit Application into our class.
3. Override start() method of Application class.

Stage
Stage in a JavaFX application is similar to the Frame in a Swing Application. It acts like a
container for all the JavaFX objects. Primary Stage is created internally by the platform.
Other stages can further be created by the application. The object of primary stage is
passed to start method. We need to call show method on the primary stage object in
order to show our primary stage. Initially, the primary Stage looks like following.
However, we can add various objects to this primary stage. The objects can only be added
in a hierarchical way i.e. first, scene graph will be added to this primaryStage and then
that scene graph may contain the nodes. A node may be any object of the user's interface
like text area, buttons, shapes, media, etc.

Scene
Scene actually holds all the physical contents (nodes) of a JavaFX
application. [Link] class provides all the methods to deal with a scene
object. Creating scene is necessary in order to visualize the contents on the stage.

At one instance, the scene object can only be added to one stage. In order to implement
Scene in our JavaFX application, we must import [Link] package in our code. The
Scene can be created by creating the Scene class object and passing the layout object
into the Scene class constructor. We will discuss Scene class and its method later in detail.

Scene Graph
Scene Graph exists at the lowest level of the hierarchy. It can be seen as the collection of
various nodes. A node is the element which is visualized on the stage. It can be any button,
text box, layout, image, radio button, check box, etc.
The nodes are implemented in a tree kind of structure. There is always one root in the
scene graph. This will act as a parent node for all the other nodes present in the scene
graph. However, this node may be any of the layouts available in the JavaFX system.

The leaf nodes exist at the lowest level in the tree hierarchy. Each of the node present in
the scene graphs represents classes of [Link] package therefore we need to import
the package into our application in order to create a full featured javafx application.

Creating JavaFX Application


This example creates a simple JavaFX application which prints hello world on the console
on clicking the button shown on the stage.

Step 1: Extend [Link] and override start()


As we have studied earlier that start() method is the starting point of constructing a
JavaFX application therefore we need to first override start method
of [Link] class. Object of the class [Link] is passed
into the start() method therefore import this class and pass its object into start
method. [Link] needs to be imported in order to override start
method.

The code will look like following.

1. import [Link];
2. import [Link];
3. public class Hello_World extends Application{
4. @Override
5. public void start(Stage primaryStage) throws Exception {
6. // TODO Auto-generated method stub
7.
8. }
9.
10. }

Step 2: Create a Button


A button can be created by instantiating the [Link] class. For this,
we have to import this class into our code. Pass the button label text in Button class
constructor. The code will look like following.

1. import [Link];
2. [Link];
3. import [Link];
4. public class Hello_World extends Application{
5.
6. @Override
7. public void start(Stage primaryStage) throws Exception {
8. // TODO Auto-generated method stub
9. Buttonbtn1=newButton("Say, Hello World");
10.
11. }
12.
13. }
Step 3: Create a layout and add button to it
JavaFX provides the number of layouts. We need to implement one of them in order to
visualize the widgets properly. It exists at the top level of the scene graph and can be seen
as a root node. All the other nodes (buttons, texts, etc.) need to be added to this layout.

In this application, we have implemented StackPane layout. It can be implemented by


instantiating [Link] class. The code will now look like following.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. public class Hello_World extends Application{
6.
7. @Override
8. public void start(Stage primaryStage) throws Exception {
9. // TODO Auto-generated method stub
10. Button btn1=new Button("Say, Hello World");
11. StackPane root=new StackPane();
12. [Link]().add(btn1);
13.
14. }
15.
16. }

Step 4: Create a Scene


The layout needs to be added to a scene. Scene remains at the higher level in the hierarchy
of application structure. It can be created by instantiating [Link] class. We
need to pass the layout object to the scene class constructor. Our application code will
now look like following.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. public class Hello_World extends Application{
7. @Override
8. public void start(Stage primaryStage) throws Exception {
9. // TODO Auto-generated method stub
10. Button btn1=new Button("Say, Hello World");
11. StackPane root=new StackPane();
12. [Link]().add(btn1);
13. Scene scene=new Scene(root);
14. }
15.
16. }

we can also pass the width and height of the required stage for the scene in the Scene
class constructor.

Step 5: Prepare the Stage


[Link] class provides some important methods which are required to be
called to set some attributes for the stage. We can set the title of the stage. We also need
to call show() method without which, the stage won't be shown. Lets look at the code
which describes how can be prepare the stage for the application.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. public class Hello_World extends Application{
7. @Override
8. public void start(Stage primaryStage) throws Exception {
9. // TODO Auto-generated method stub
10. Button btn1=new Button("Say, Hello World");
11. StackPane root=new StackPane();
12. [Link]().add(btn1);
13. Scene scene=new Scene(root);
14. [Link](scene);
15. [Link]("First JavaFX Application");
16. [Link]();
17. }
18.
19. }

Step 6: Create an event for the button


As our application prints hello world for an event on the button. We need to create an
event for the button. For this purpose, call setOnAction() on the button and define a
anonymous class Event Handler as a parameter to the method.

Inside this anonymous class, define a method handle() which contains the code for how
the event is handled. In our case, it is printing hello world on the console.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. public class Hello_World extends Application{
9. @Override
10. publicvoid start(Stage primaryStage) throws Exception {
11. // TODO Auto-generated method stub
12. Button btn1=new Button("Say, Hello World");
13. [Link](new EventHandler<ActionEvent>() {
14.
15. @Override
16. publicvoid handle(ActionEvent arg0) {
17. // TODO Auto-generated method stub
18. [Link]("hello world");
19. }
20. });
21. StackPane root=new StackPane();
22. [Link]().add(btn1);
23. Scene scene=new Scene(root,600,400);
24. [Link](scene);
25. [Link]("First JavaFX Application");
26. [Link]();
27. }
28. }

Step 7: Create the main method


Till now, we have configured all the necessary things which are required to develop a basic
JavaFX application but this application is still incomplete. We have not created main
method yet. Hence, at the last, we need to create a main method in which we will launch
the application i.e. will call launch() method and pass the command line arguments (args)
to it. The code will now look like following.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. public class Hello_World extends Application{
9. @Override
10. public void start(Stage primaryStage) throws Exception {
11. // TODO Auto-generated method stub
12. Button btn1=new Button("Say, Hello World");
13. [Link](new EventHandler<ActionEvent>() {
14. @Override
15. public void handle(ActionEvent arg0) {
16. // TODO Auto-generated method stub
17. [Link]("hello world");
18. }
19. });
20. StackPane root=new StackPane();
21. [Link]().add(btn1);
22. Scene scene=new Scene(root,600,400);
23. [Link]("First JavaFX Application");
24. [Link](scene);
25. [Link]();
26. }
27. publicstaticvoid main (String[] args)
28. {
29. launch(args);
30. }
31. }

The Application will produce the following output on the screen.

JavaFX Layouts
Layouts are the top level container classes that define the UI styles for scene graph objects.
Layout can be seen as the parent node to all the other nodes. JavaFX provides various
layout panes that support different styles of layouts.
In JavaFX, Layout defines the way in which the components are to be seen on the stage.
It basically organizes the scene-graph nodes. We have several built-in layout panes in
JavaFX that are HBox, VBox, StackPane, FlowBox, AnchorPane, etc. Each Built-in layout is
represented by a separate class which needs to be instantiated in order to implement that
particular layout pane.

All these classes belong to [Link] package. [Link] class


is the base class for all the built-in layout classes in JavaFX.

Layout Classes
[Link] Package provides various classes that represents the layouts. The
classes are described in the table below.

Class Description

BorderPane Organizes nodes in top, left, right, centre and the bottom of the screen.

FlowPane Organizes the nodes in the horizontal rows according to the available
horizontal spaces. Wraps the nodes to the next line if the horizontal
space is less than the total width of the nodes

GridPane Organizes the nodes in the form of rows and columns.

HBox Organizes the nodes in a single row.

Pane It is the base class for all the layout classes.

StackPane Organizes nodes in the form of a stack i.e. one onto another

VBox Organizes nodes in a vertical column.

Steps to create layout


In order to create the layouts, we need to follow the following steps.

1. Instantiate the respective layout class, for example, HBox root = new HBox();
2. Setting the properties for the layout, for example, [Link](20);
3. Adding nodes to the layout object, for
example, [Link]().addAll(<NodeObjects>);

JavaFX BorderPane
BorderPane arranges the nodes at the left, right, centre, top and bottom of the screen. It
is represented by [Link] class. This class provides various
methods like setRight(), setLeft(), setCenter(), setBottom() and setTop() which are
used to set the position for the specified nodes. We need to instantiate BorderPane class
to create the BorderPane layout.

Properties
The properties of BorderPane class along with their setter methods are given in the table
below.

Type Property Setter Methods Description

Node Bottom setBottom() Add the node to the bottom of the screen

Node Centre setCentre() Add the node to the centre of the screen

Node Left setLeft() Add the node to the left of the screen

Node Right setRight() Add the node to the right of the screen

Node Top setTop() Add the node to the top of the screen

Constructors
There are the following constructors in the class.

1. BorderPane() : create the empty layout


2. BorderPane(Node Center) : create the layout with the center node
3. BorderPane(Node Center, Node top, Node right, Node bottom, Node left) : create
the layout with all the nodes

Example
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link].*;
5. import [Link];
6. public class Label_Test extends Application {
7.
8. @Override
9. public void start(Stage primaryStage) throws Exception {
10. BorderPane BPane = new BorderPane();
11. [Link](new Label("This will be at the top"));
12. [Link](new Label("This will be at the left"));
13. [Link](new Label("This will be at the Right"));
14. [Link](new Label("This will be at the Centre"));
15. [Link](new Label("This will be at the bottom"));
16. Scene scene = new Scene(BPane,600,400);
17. [Link](scene);
18. [Link]();
19. }
20. public static void main(String[] args) {
21. launch(args);
22. }
23.
24. }
JavaFX HBox
HBox layout pane arranges the nodes in a single row. It is represented
by [Link] class. We just need to instantiate HBox class in order to
create HBox layout.

Properties
The Properties of the class along with their setter methods are given in the table below.

Property Description Setter Methods

alignment This represents the alignment of the nodes. setAlignment(Double)


fillHeight This is a boolean property. If you set this setFillHeight(Double)
property to true the height of the nodes will
become equal to the height of the HBox.

spacing This represents the space between the nodes in setSpacing(Double)


the HBox. It is of double type.

Constructors
The HBox class contains two constructors that are given below.

1. new HBox() : create HBox layout with 0 spacing


2. new Hbox(Double spacing) : create HBox layout with a spacing value

Example

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. public class Label_Test extends Application {
7. @Override
8. public void start(Stage primaryStage) throws Exception {
9. Button btn1 = new Button("Button 1");
10. Button btn2 = new Button("Button 2");
11. HBox root = new HBox();
12. Scene scene = new Scene(root,200,200);
13. [Link]().addAll(btn1,btn2);
14. [Link](scene);
15. [Link]();
16. }
17. public static void main(String[] args) {
18. launch(args);
19. }
20.
21. }

Example : Setting the space among the nodes.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. public class Label_Test extends Application {
7. @Override
8. public void start(Stage primaryStage) throws Exception {
9. Button btn1 = new Button("Button 1");
10. Button btn2 = new Button("Button 2");
11. HBox root = new HBox();
12. Scene scene = new Scene(root,200,200);
13. [Link]().addAll(btn1,btn2);
14. [Link](40);
15. [Link](scene);
16. [Link]();
17. }
18. public static void main(String[] args) {
19. launch(args);
20. }
21.
22. }

JavaFX VBox
Instead of arranging the nodes in horizontal row, Vbox Layout Pane arranges the nodes
in a single vertical column. It is represented by [Link] class which
provides all the methods to deal with the styling and the distance among the nodes. This
class needs to be instantiated in order to implement VBox layout in our application.

Properties
This Method Provides various properties which are described in the table below.
Property Description Setter Methods

Alignment This property is for the alignment of the setAlignement(Double)


nodes.

FillWidth This property is of the boolean type. The setFillWidth(boolean)


Widtht of resizeable nodes can be made equal
to the Width of the VBox by setting this
property to true.

Spacing This property is to set some spacing among setSpacing(Double)


the nodes of VBox.

Constructors

1. VBox() : creates layout with 0 spacing


2. Vbox(Double spacing) : creates layout with a spacing value of double type
3. Vbox(Double spacing, Node? children) : creates a layout with the specified spacing
among the specified child nodes
4. Vbox(Node? children) : creates a layout with the specified nodes having 0 spacing
among them

Example

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. public class Label_Test extends Application {
7. @Override
8. public void start(Stage primaryStage) throws Exception {
9. Button btn1 = new Button("Button 1");
10. Button btn2 = new Button("Button 2");
11. VBox root = new VBox();
12. Scene scene = new Scene(root,200,200);
13. [Link]().addAll(btn1,btn2);
14. [Link](scene);
15. [Link]();
16. }
17. public static void main(String[] args) {
18. launch(args);
19. }
20.
21. }

Output:

JavaFX StackPane
The StackPane layout pane places all the nodes into a single stack where every new node
gets placed on the top of the previous node. It is represented
by [Link] class. We just need to instantiate this class to
implement StackPane layout into our application.
Properties
The class contains only one property that is given below along with its setter method.

Property Description Setter Method

alignment It represents the default alignment of setAlignment(Node child,


children within the StackPane's width and Pos value)
height setAlignment(Pos value)

Constructors
The class contains two constructors that are given below.

1. StackPane()
2. StackPane(Node? Children)

Example

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. public class Label_Test extends Application {
7. @Override
8. public void start(Stage primaryStage) throws Exception {
9. Button btn1 = new Button("Button 1 on bottom ");
10. Button btn2 = new Button("Button 2 on top");
11. StackPane root = new StackPane();
12. Scene scene = new Scene(root,200,200);
13. [Link]().addAll(btn1,btn2);
14. [Link](scene);
15. [Link]();
16. }
17. public static void main(String[] args) {
18. launch(args);
19. }
20.
21. }

Output:

JavaFX GridPane
GridPane Layout pane allows us to add the multiple nodes in multiple rows and columns.
It is seen as a flexible grid of rows and columns where nodes can be placed in any cell of
the grid. It is represented by [Link] class. We just need to
instantiate this class to implement GridPane.

Properties
The properties of the class along with their setter methods are given in the table below.
Property Description Setter Methods

alignment Represents the alignment of the grid within the GridPane. setAlignment(Pos valu

gridLinesVisible This property is intended for debugging. Lines can be setGridLinesVisible(Boo


displayed to show the gidpane's rows and columns by value)
setting this property to true.

hgap Horizontal gaps among the columns setHgap(Double value

vgap Vertical gaps among the rows setVgap(Double value)

Constructors
The class contains only one constructor that is given below.

o Public GridPane(): creates a gridpane with 0 hgap/vgap.

Example:

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. public class Label_Test extends Application {
9. @Override
10. public void start(Stage primaryStage) throws Exception {
11. Label first_name=new Label("First Name");
12. Label last_name=new Label("Last Name");
13. TextField tf1=new TextField();
14. TextField tf2=new TextField();
15. Button Submit=new Button ("Submit");
16. GridPane root=new GridPane();
17. Scene scene = new Scene(root,400,200);
18. [Link](0, first_name,tf1);
19. [Link](1, last_name,tf2);
20. [Link](2, Submit);
21. [Link](scene);
22. [Link]();
23. }
24. public static void main(String[] args) {
25. launch(args);
26. }
27.
28. }

Output:

JavaFX UI Controls
The graphical user interface of every desktop application mainly considers UI elements,
layouts and behaviour.

The UI elements are the one which are actually shown to the user for interaction or
information exchange. Layout defines the organization of the UI elements on the screen.
Behaviour is the reaction of the UI element when some event is occurred on it.

However, the package [Link] provides all the necessary classes for the UI
components like Button, Label, etc. Every class represents a specific UI control and defines
some methods for their styling.
SN Control Description

1 Label Label is a component that is used to define a simple text on


the screen. Typically, a label is placed with the node, it
describes.

2 Button Button is a component that controls the function of the


application. Button class is used to create a labelled button.

3 RadioButton The Radio Button is used to provide various options to the


user. The user can only choose one option among all. A radio
button is either selected or deselected.

4 CheckBox Check Box is used to get the kind of information from the
user which contains various choices. User marked the
checkbox either on (true) or off(false).

5 TextField Text Field is basically used to get the input from the user in
the form of text. [Link] represents
TextField

6 PasswordField PasswordField is used to get the user's password. Whatever


is typed in the passwordfield is not shown on the screen to
anyone.

7 HyperLink HyperLink are used to refer any of the webpage through


your appication. It is represented by the
class [Link]

8 Slider Slider is used to provide a pane of options to the user in a


graphical form where the user needs to move a slider over
the range of values to select one of them.

9 ProgressBar Progress Bar is used to show the work progress to the user.
It is represented by the
class [Link].

10 ProgressIndicator Instead of showing the analogue progress to the user, it


shows the digital progress so that the user may know the
amount of work done in percentage.
11 ScrollBar JavaFX Scroll Bar is used to provide a scroll bar to the user
so that the user can scroll down the application pages.

12 Menu JavaFX provides a Menu class to implement menus. Menu is


the main component of any application.

13 ToolTip JavaFX ToolTip is used to provide hint to the user about any
component. It is mainly used to provide hints about the text
fields or password fields being used in the application.

JavaFX Label
[Link] class represents label control. As the name suggests, the label
is the component that is used to place any text information on the screen. It is mainly
used to describe the purpose of the other components to the user. You can not set a
focus on the label using the Tab key.

Package: [Link]

Constructors:

1. Label(): creates an empty Label


2. Label(String text): creates Label with the supplied text
3. Label(String text, Node graphics): creates Label with the supplied text and graphic
s

Adding a Node to the scene graph


The following code implements Label into our Application.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. public class LabelTest extends Application {
7. @Override
8. public void start(Stage primaryStage) throws Exception {
9. // TODO Auto-generated method stub
10. Label my_label=new Label("This is an example of Label");
11. StackPane root = new StackPane();
12. Scene scene=new Scene(root,300,300);
13. [Link]().add(my_label);
14. [Link](scene);
15. [Link]("Label Class Example");
16. [Link]();
17. }
18. public static void main(String[] args) {
19. launch(args);
20. }
21. }

Output:
Displaying image in a Label
JavaFX allows us to display some graphics next to the label text. There is a constructor in
the Label class in which, we can pass any image along with the label text. The example
given below is displaying the image in a Label.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. public class LabelTest extends Application {
10. @Override
11. public void start(Stage primaryStage) throws Exception {
12. // TODO Auto-generated method stub
13. StackPane root = new StackPane();
14. FileInputStream input= new FileInputStream("/home/santos/Desktop/JavaF
X/Images/colored_label.png");
15. Image image = new Image(input);
16. ImageView imageview=new ImageView(image);
17. Label my_label=new Label("Home",imageview);
18. Scene scene=new Scene(root,300,300);
19. [Link]().add(my_label);
20. [Link](scene);
21. [Link]("Label Class Example");
22. [Link]();
23. }
24. public static void main(String[] args) {
25. launch(args);
26. }
27. }
Output:

JavaFX Button
JavaFX button control is represented by [Link] class. A button is a
component that can control the behaviour of the Application. An event is generated
whenever the button gets clicked.

How to create a Button?


Button can be created by instantiating Button class. Use the following line to create button
object.

1. Button btn = new Button("My Button");

Adding a Button to the scene graph


To visualize the button on the screen, we must attach it to the scene object. The following
code creates a button and adds it to the scene object.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. public class ButtonTest extends Application {
7. @Override
8. public void start(Stage primaryStage) throws Exception {
9. StackPane root = new StackPane();
10. Button btn=new Button("This is a button");
11. Scene scene=new Scene(root,300,300);
12. [Link]().add(btn);
13. [Link](scene);
14. [Link]("Button Class Example");
15. [Link]();
16. }
17. public static void main(String[] args) {
18. launch(args);
19. }
20. }

Output:
Setting the Text of the Button
There are two ways of setting the text on the button.

1. Passing the text into the class constructor


2. By calling setText("text") method

Wrapping Button Text


We can wrap the text of the button into multiple lines if the text to be displayed is too
long. This can be done by calling a setter method setWrapText(boolean) on the instance
of Button class. Pass the boolean value true in the method wherever required.

1. [Link](true);

Setting the image on the button


Button class contains a constructor which can accept graphics along with the text
displayed on the button. The following code implements image on the button.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. public class ButtonTest extends Application {
10. @Override
11. public void start(Stage primaryStage) throws Exception {
12. FileInputStream input=new FileInputStream("/home/javatpoint/Desktop/Jav
aFX/Images/colored_label.png");
13. Image image = new Image(input);
14. ImageView img=new ImageView(image);
15.
16. StackPane root = new StackPane();
17. Button btn=new Button("Button 1",img);
18. [Link](true);
19. Scene scene=new Scene(root,300,300);
20. [Link]().add(btn);
21. [Link](scene);
22. [Link]("Button Class Example");
23. [Link]();
24.
25. }
26. public static void main(String[] args) {
27. launch(args);
28. }
29. }

Output:
Using setGraphic() method:

Button class also provides an instance method named setGraphic(). We have to pass the
image view object in this method. The following code implements setGraphic() method.

1. package application;
2.
3. import [Link];
4.
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10. import [Link];
11. import [Link];
12. public class ButtonTest extends Application {
13. @Override
14. public void start(Stage primaryStage) throws Exception {
15. // TODO Auto-generated method stub
16. FileInputStream input=new FileInputStream("/home/javatpoint/Desktop/Jav
aFX/Images/colored_label.png");
17. Image image = new Image(input);
18. ImageView img=new ImageView(image);
19. StackPane root = new StackPane();
20. Button btn=new Button();
21. [Link](img);
22. [Link](true);
23. Scene scene=new Scene(root,300,300);
24. [Link]().add(btn);
25. [Link](scene);
26. [Link]("Button Class Example");
27. [Link]();
28.
29. }
30. public static void main(String[] args) {
31. launch(args);
32. }
33. }

Output:

Button Action
Button class provides setOnAction() methodwhich is used to set the action for the button
click event. An object of the anonymous class implementing the handle() method, is
passed in this method as a parameter.

. The following code implements the Button event.


1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10. import [Link];
11. public class LabelTest extends Application {
12. @Override
13. public void start(Stage primaryStage) throws Exception {
14. FileInputStream input=new FileInputStream("/home/santos/Desktop/JavaFX
/Images/colored_label.png");
15. Image image = new Image(input);
16. ImageView img=new ImageView(image);
17. StackPane root = new StackPane();
18. Button btn=new Button();
19. [Link](img);
20. [Link](true);
21. [Link](new EventHandler<ActionEvent>() {
22. @Override
23. publicvoid handle(ActionEvent arg0) {
24. [Link]("Button clicked");
25. }
26. } );
27. Scene scene=new Scene(root,300,300);
28. [Link]().add(btn);
29. [Link](scene);
30. [Link]("Button Class Example");
31. [Link]();
32. }
33. public static void main(String[] args) {
34. launch(args);
35. }
36. }

Output:

Button Effects
We can apply the effects to a Button. The effects are provided
by [Link] package. The following code shows how the drop shadow effect
can be applied to a button.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10. import [Link];
11. import [Link];
12. public class ButtonTest extends Application {
13. @Override
14. public void start(Stage primaryStage) throws Exception {
15. FileInputStream input=new FileInputStream("/home/santos/Desktop/JavaFX
/Images/colored_label.png");
16. Image image = new Image(input);
17. ImageView img=new ImageView(image);
18. DropShadow shadow = new DropShadow();
19. StackPane root = new StackPane();
20. Button btn=new Button();
21. [Link](shadow);
22. [Link](img);
23. [Link](true);
24. [Link](new EventHandler<ActionEvent>() {
25.
26. @Override
27. public void handle(ActionEvent arg0) {
28. [Link]("Button clicked");
29. }
30. } );
31. Scene scene=new Scene(root,300,300);
32. [Link]().add(btn);
33. [Link](scene);
34. [Link]("Button Class Example");
35. [Link]();
36.
37. }
38. public static void main(String[] args) {
39. launch(args);
40. }
41. }

Output:
JavaFX RadioButton
The Radio Button is used to provide various options to the user. The user can only choose
one option among all. A radio button is either selected or deselected. It can be used in a
scenario of multiple choice questions in the quiz where only one option needs to be
chosen by the student.

The following code shows how one radio button is selected from a toggle group.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. public class RadioButtonTest extends Application {
8. public static void main(String[] args) {
9. launch(args);
10. }
11. @Override
12. public void start(Stage primaryStage) throws Exception {
13. // TODO Auto-generated method stub
14. ToggleGroup group = new ToggleGroup();
15. RadioButton button1 = new RadioButton("option 1");
16. RadioButton button2 = new RadioButton("option 2");
17. RadioButton button3 = new RadioButton("option 3");
18. RadioButton button4 = new RadioButton("option 4");
19. [Link](group);
20. [Link](group);
21. [Link](group);
22. [Link](group);
23. VBox root=new VBox();
24. [Link](10);
25. [Link]().addAll(button1,button2,button3,button4);
26. Scene scene=new Scene(root,400,300);
27. [Link](scene);
28. [Link]("Radio Button Example");
29. [Link]();
30. }
31. }

Output:
JavaFX CheckBox
The Check Box is used to provide more than one choices to the user. It can be used in a
scenario where the user is prompted to select more than one option or the user wants to
select multiple options.

It is different from the radiobutton in the sense that, we can select more than one
checkboxes in a scenerio.

Instantiate [Link] class to implement CheckBox.

Use the following line in the code to create a blank CheckBox.

1. CheckBox checkbox = new CheckBox();

Use the following line to attach a label with the checkbox.


1. CheckBox checkbox = new CheckBox("Label Name");

We can change the CheckBox Label at any time by calling an instance


method setText("text"). We can make it selected by calling setSelected("true")

The following code implements CheckBox into our application.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. public class CheckBoxTest extends Application {
8. public static void main(String[] args) {
9. launch(args);
10. }
11. @Override
12. public void start(Stage primaryStage) throws Exception {
13. // TODO Auto-generated method stub
14. Label l = new Label("What do you listen: ");
15. CheckBox c1 = new CheckBox("Radio one");
16. CheckBox c2 = new CheckBox("Radio Mirchi");
17. CheckBox c3 = new CheckBox("Red FM");
18. CheckBox c4 = new CheckBox("FM GOLD");
19. HBox root = new HBox();
20. [Link]().addAll(l,c1,c2,c3,c4);
21. [Link](5);
22. Scene scene=new Scene(root,800,200);
23. [Link](scene);
24. [Link]("CheckBox Example");
25. [Link]();
26. }
27. }

Output:

JavaFX TextField
Text Field is basically used to get the input from the user in the form of
text. [Link] represents TextField. It provides various methods to
deal with textfields in JavaFX. TextField can be created by instantiating TextField class.

Lets see an example where the user is shown the two text boxes and prompted to fill its
user-id and password.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. public class TextFieldTest extends Application {
9. public static void main(String[] args) {
10. launch(args);
11. }
12.
13. @Override
14. public void start(Stage primaryStage) throws Exception {
15. // TODO Auto-generated method stub
16. Label user_id=new Label("User ID");
17. Label password = new Label("Password");
18. TextField tf1=new TextField();
19. TextField tf2=new TextField();
20. Button b = new Button("Submit");
21. GridPane root = new GridPane();
22. [Link](0, user_id, tf1);
23. [Link](1, password, tf2);
24. [Link](2, b);
25. Scene scene=new Scene(root,800,200);
26. [Link](scene);
27. [Link]("Text Field Example");
28. [Link]();
29. }
30. }

Output:
Getting Text field Data
TextField class provides an instance method getText() to retrieve the textfield data. It
returns String object which can be used to save the user details in database.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. public class TextFieldExample extends Application {
9. public static void main(String[] args) {
10. launch(args);
11. }
12. @Override
13. public void start(Stage primaryStage) throws Exception {
14. // TODO Auto-generated method stub
15. Label user_id=new Label("User ID");
16. Label password = new Label("Password");
17. TextField tf1=new TextField();
18. TextField tf2=new TextField();
19. Button b = new Button("Submit");
20. [Link](e-
>[Link]("You entered: User_ID: "+[Link]()+""+"Password: "+tf2.g
etText()));
21. GridPane root = new GridPane();
22. [Link](0, user_id, tf1);
23. [Link](1, password, tf2);
24. [Link](2, b);
25. Scene scene=new Scene(root,300,200);
26. [Link](scene);
27. [Link]("Text Field Example");
28. [Link]();
29. }
30. }

Output:
JavaFX PasswordField
Passwordfield can be created by instantiating [Link] class.
PasswordField class contains a method named as setPromptText() for showing a prompt
text to the user in password field. The data written in the passwordfield is retrieved
by getText() method.

Example:

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. public class PasswordFieldTest extends Application {
10. public static void main(String[] args) {
11. launch(args);
12. }
13. @Override
14. public void start(Stage primaryStage) throws Exception {
15. Label user_id=new Label("User ID");
16. Label password = new Label("Password");
17. TextField tf=new TextField();
18. PasswordField pf=new PasswordField();
19. [Link]("Enter Password");
20. Button b = new Button("Submit");
21. GridPane root = new GridPane();
22. [Link](0, user_id, tf);
23. [Link](1, password, pf);
24. [Link](5, b);
25. Scene scene=new Scene(root,300,200);
26. [Link](scene);
27. [Link]("PasswordField Example");
28. [Link]();
29. }
30. }

Output:

JavaFX Menu
JavaFX provides a Menu class to implement menus. Menu is the main component of a any
application. In JavaFX, [Link] class provides all the methods to deal
with menus. This class needs to be instantiated to create a Menu.

The following sample of code shows the implementation of JavaFX menu.

1. ManuBar menubar = new MenuBar(); //creating MenuBar


2. Menu MenuName = new Menu("Menu Name"); //creating Menu
3. MenuItem MenuItem1 = new MenuItem("Menu Item 1 Name"); //creating Menu
Item
4. [Link]().add(MenuItem1); //adding Menu Item to the Menu
5. [Link]().add(MenuName); //adding Menu to the MenuBar
EXAMPLE:

1. import [Link];
2. import [Link];
3. import [Link].*;
4. import [Link];
5. import [Link];
6. public class MenuExample extends Application {
7. public static void main(String[] args) {
8. launch(args);
9. }
10. @Override
11. public void start(Stage primaryStage) throws Exception {
12. BorderPane root = new BorderPane();
13. Scene scene = new Scene(root,200,300);
14. MenuBar menubar = new MenuBar();
15. Menu FileMenu = new Menu("File");
16. MenuItem filemenu1=new MenuItem("new");
17. MenuItem filemenu2=new MenuItem("Save");
18. MenuItem filemenu3=new MenuItem("Exit");
19. Menu EditMenu=new Menu("Edit");
20. MenuItem EditMenu1=new MenuItem("Cut");
21. MenuItem EditMenu2=new MenuItem("Copy");
22. MenuItem EditMenu3=new MenuItem("Paste");
23. [Link]().addAll(EditMenu1,EditMenu2,EditMenu3);
24. [Link](menubar);
25. [Link]().addAll(filemenu1,filemenu2,filemenu3);
26. [Link]().addAll(FileMenu,EditMenu);
27. [Link](scene);
28. [Link]();
29.
30. }
31. }

Output:
JavaFX Tooltip
JavaFX Tool tip is used to provide hint to the user about any component. It is mainly used
to provide hints about the text fields or password fields being used in the application.

It can be created by instantiating [Link] class. The following code


implements Tooltip about a password field to the user.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. public class ProgressBarTest extends Application {
8. public void start(Stage primaryStage) throws Exception {
9. // TODO Auto-generated method stub
10. PasswordField pf = new PasswordField();
11. Tooltip tool=new Tooltip();
12. StackPane root = new StackPane();
13. [Link]("Information");
14. [Link](tool);
15. [Link]().add(pf);
16. Scene scene = new Scene(root,300,200);
17. [Link](scene);
18. [Link]("ToolTip Example");
19. [Link]();
20. }
21. public static void main(String[] args) {
22. launch(args);
23. }
24. }

Output:
Java Swing Vs JavaFX
Aspect Java Swing JavaFX

Optimized for complex Hardware-accelerated,


Performance
UIs, efficient rendering excellent performance.

Richness of UI Rich library with Modern and extensive


Components advanced components UI component set

More extensive, may


Ease of Use and Modern UI components,
have a steeper learning
Learning Curve may be more complex.
curve.

Compatibility with Widely compatible, Seamlessly integrated


Modern Java well-supported with modern Java.

Community Support Strong community, Growing community,


and Maintenance actively maintained actively maintained.

Desktop-focused,
Cross-platform
Platform Compatibility limited web/mobile
(desktop, web, mobile)
support

You might also like