0% found this document useful (0 votes)
27 views68 pages

Unit 5

The document provides an overview of JavaFX, focusing on event handling, controls, and components for developing rich client applications. It covers the structure of JavaFX applications, including key concepts like Stage, Scene, and Node, as well as methods for handling mouse and keyboard events. Additionally, it includes programming examples to illustrate the creation of JavaFX applications and the use of various UI controls.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views68 pages

Unit 5

The document provides an overview of JavaFX, focusing on event handling, controls, and components for developing rich client applications. It covers the structure of JavaFX applications, including key concepts like Stage, Scene, and Node, as well as methods for handling mouse and keyboard events. Additionally, it includes programming examples to illustrate the creation of JavaFX applications and the use of various UI controls.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 68

CS3391 - OBJECT ORIENTED PROGRAMMING

UNIT V - JAVAFX EVENT HANDLING, CONTROLS AND COMPONENTS

JAVAFX Events and Controls: Event Basics – Handling Key and Mouse Events. Controls:
Checkbox, ToggleButton – RadioButtons – ListView – ComboBox – ChoiceBox – Text Controls
– ScrollPane. Layouts – FlowPane – HBox and VBox – BorderPane – StackPane – GridPane.
Menus – Basics – Menu – Menu bars – MenuItem.

Basicas of JAVAFX
• JavaFX was originally developed by Chris Oliver, when he was working for a company
named See Beyond Technology Corporation, which was later acquired by Sun
Microsystems in the year 2005.

• JavaFX is a set of graphics and media packages that enables developers to design, create,
test, debug, and deploy rich client applications that operate consistently across different
platforms.

• JavaFX makes it easier to create desktop applications and

Games in Java.

• JavaFX has replaced Swing as the recommended GUI toolkit for Java. Furthermore,
JavaFX is more consistent in its design than Swing, and has more features.

Features of JAVAFX

1) JavaFX library is written in java. Hence developer find it easy to learn and write the
applications in JAVAFX.

2) JAVAFX library creates UI controls using which any GUI based application can be
developed.

3) It provides the classes for 2D and 3D graphics.

4) JavaFX contains a set of ready-to-use chart components, so you don't have to code that
from scratch every time you need a basic chart.

5) JavaFX components can be styled using CSS.


6) It provides the support for integrating audio, videos, and web applications.

We need to import javafx.application.Application class in every JavaFX application.

Every JAVAFX program is divided into three main components - Stage, Scene and Node
and Scene graph.

(1) Stage; Stage is like main frame of the program. It acts as a container for all the objects
of JavaFX application. The most commonly used stage is a PrimaryStage. It is created
internally by the platform. The object of PrimaryStage is passed to the start() method. There
is a show method that is used to show the stage.

(2) Scene: The Javafx.scene.Scene class provides the methods to deal with the scene object.
It contains the nodes or all the contents of Scene graph. The scene is created by instantiating
the Scene class.

(3) Scene Graph and Node: The scene graph is a collection of various nodes. The node is
an element that can be visualized on the screen. The node can be button, textbox, radio
button and so on.

The nodes are implemented in tree like manner. There is one root node. This will be the
parent node of all the other nodes.

Important Methods used in JavaFX Application

(1) start(): This is the method in which we write the code for JavaFX application. The
construct for this method is

public abstract void start(Stage primaryStage)

(2) launch() In the main method, you have to launch the application using the launch()
method. This method internally calls the start() method of the Application class. Since the
launch() method is static, you need to call it from a static method such as main()

Writing First JavaFX Application Program


We can create an application program in NetBean IDE or Eclipse IDE. Following steps are
used to create this application program -

Prerequisite: Before executing the JavaFX application program, you need to have following
things installed in your PC

i) Java 8

ii) NetBeans 8

Step 1: From the File menu, choose New Project. Then select JavaFX application category,
choose JavaFX Application. Click Next.
Then the code can be written as follows

package myjavafxapplication;

import javafx.application.Application;

import static javafx.application. Application.launch;

import javafx.scene.Scene;
import javafx.scene.control.Label;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start (Stage primaryStage) {

Label L= new Label(" WELCOME TO FIRST APPLICATION USING JAVAFX");

Scene scene = new Scene(L, 300, 300);

primaryStage.setTitle("FIRST DEMO PROGRAM");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);

Step 2: Now right click on the source file and click on Run File As. The output will be
displayed as follows

Output
Program Explanation: In above program,

1. We have to import javafx.application.Application package to support the Application


class.

2. Then we need to import the classes for supporting - Stage Scene, Label component and
launch method. Hence we add following lines in our code.

import static javafx.application. Application.launch;

import javafx.scene.Scene;

import javafx.scene.control.Label;

import javafx.stage.Stage;

3. Our class must extend Application class.

4. Then we write overridden start() method in which the entire application code is written.
The primaryStage is passed as a framework to this start method as a parameter. Note that
these are all standard steps for any JavaFX application program.

5. Then we have -

Step 1: Created a Label component.

Label L=new Label(" WELCOME TO FIRST APPLICATION USING JAVAFX"); Step 2:


Created a Scene using new operator and placed the Label component on Scene. Scene scene
= new Scene(L, 300, 300);

Step 3: Using setScene method we have set this scene for Stage
primaryStage.setScene(scene);

Step 4: If you want to display the title for your application page, then it is possible by using
setTitle method for the Stage component. Keep it in mind that here stage is something like
a frame on which scene, UI components are placed.

primaryStage.setTitle("FIRST DEMO PROGRAM");

Step 5: Finally any component can be made visible by using show() method.

primaryStage.show();

6. Then write the main() method which in turn will call launch() method to call your start()
method.

public static void main(String[] args) {

launch(args);

That's it. Now run your application program and a Label component with some message
will be displayed as an output.

Panes and UI Controls


• Pane is a container class using which the UI components can be placed at any desired
location with any desired size.

• Generally you place a node inside a pane and then place pane into a scene. Actually node
is any visual component such as UI controls, shapes, or a image view.

• UI Controls refer to label, button, Checkbox, radio buttons and so on.

• Shapes refer to lines, rectangle, circle and so on.

• A Scene can be displayed in a Stage. The relationship between node, Pane, Scene, Stage
is shown by following figure.
• Programming Example

package myjavafxapplication;

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.layout.StackPane;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start (Stage primaryStage)

{ Button btn = new Button("Click Me");

StackPane root = new StackPane();

root.getChildren().add(btn);

Scene scene = new Scene(root, 300, 250);

primaryStage.setTitle("Demo Program");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);

Output
Program Explanation: In above program,

1) We have created a Pane named StackPane, and added a button component as a child of
the pane. For that purpose we use getChildren() method.

2) The StackPane places the nodes in t he center of the pane on top of each other. Here,
there is only one node in the pane. The use of Pane allows the button component to be
displayed with its preferred size.

Property Binding
• JavaFX introduces a new concept called binding property that enables a target object to be
bound to a source object.

• If the value in the source object changes, the target property is also changed automatically.

• The target object is simply called a binding object or a binding property.

• A target listens to the changes in the source and automatically updates itself once a change
is made in the source. A target binds with a source using the bind method as follows:

target.bind(source);

• The bind method is defined in the javafx.beans.property.Property interface.

• A binding property (target) is an instance of javafx.beans.property.Property.

• A source object is an instance of the javafx.beans.value.ObservableValue interface.


Event Basics

• Event means any activity that interrupts the current ongoing activity. For example: when
user clicks button then it generates an event. To respond to button click we need to write the
code to process the button clicking action.

• Event Source Object : The object that generates the event is called event source object.
For example- if the event gets generated on clicking the button, then button is the event
source object.

• Event Handler: The event handling code written to process the generated event is called
event handler.

• Event Listener: The task of handling an event is carried out by event listener. When an
event occurs, first of all an event object of the appropriate type is created. This object is
then passed to a Listener. A listener must implement the interface that has the method for
event handling.

Registering Handlers and Handling Events

• JavaFX has just one interface for all kinds of Event Handlers.

• It is an instance of the EventHandler<T extends Event> interface. This interface defines


the common behavior for all handlers. <T extends Event> denotes that T is a generic type
that is a subtype of Event.

• The EventHandler object handler must be registered with the event source object using the
method source.setOnAction(handler).

• The EventHandler<ActionEvent> interface contains the handle(ActionEvent) method for


abc processing the action event. We have to write the handler class that must override this
method to respond to the event. Hence we must import javafx.event.EventHandler class in
our application program.

• The event Class hierarchy is as shown below -

• There are user actions that are associated with some source objects. For these actions
particular event is fired. The JavaFX associate some setOnXXX methods for registering
these events. The list of such user actions, source objects and setOnXXX methods are
enlisted in the following table.

• Java makes use of delegation based model for event handling and registration. This model
is as shown below.
The event handling process is a two step process. It performs following functionalities –

(1) The handler object is an instance of appropriate EventHandler interface. The


EventHandler interface is defined as EventHandler<T extends Event>. It contains handle()
function for processing the event.

(2) The handler object is registered by the source object. The registration methods depend
on the event type. For ActionEvent, the method is setOnAction. For a mouse pressed event,
the method is setOnMousePressed. For a key pressed event, the method is
setOnKeyPressed.

For example

Button button = new Button("Click Me");

//Event object is button

button.setOnAction(new EventHandler <ActionEvent>() //Event registration

public void handle (ActionEvent event)

………

……...

Following is a complete JavaFX program, that displays the message on clicking the button.
Thus button click event is handled in the following program.

Programming Example

package myjavafxapplication;

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.layout.HBox;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;

import javafx. stage. Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start(Stage primaryStage)

{ HBox root = new HBox();

Button button = new Button("Click Me");

button.setOnAction(new EventHandler <ActionEvent>()

public void handle (ActionEvent event)

System.out.println("Button is clicked!!");

};

root.getChildren().add(button);

Scene scene = new Scene(root,300,200);

primaryStage.setScene(scene);

primaryStage.setTitle("Event Handling Demo");

primaryStage.show();

public static void main(String[] args) {

launch(args);
}

Output

On clicking the above button, we get following message in the output window

Handling Key and Mouse Events

Handling Mouse Event

Mouse event is fired when the mouse button is pressed, released, clicked, moved or dragged
on the node.

Following table shows the user actions and associated event handling activities -
Various mehods for MouseEvent class are enlisted in the following table

There are Four constants-PRIMARY, SECONDARY, MIDDLE, and NONE - are defined
in MouseButton to indicate the left, right, middle, and none mouse buttons.
Programming Example

package myjavafxapplication;

import javafx.application. Application;

import javafx.event.EventHandler;

import javafx.scene.Group;

import javafx.scene.Scene;

import javafx.scene.input. MouseEvent;

import javafx.scene.paint.Color;

import javafx.scene.shape: Rectangle;

import javafx.scene.text.Text;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start(Stage primaryStage)

{ Rectangle rect = new

Rectangle(50,50,100,100); rect.setArcWidth(20);

rect.setArcHeight(20);

rect.setFill(Color.BLUE);

Text text = new Text (20,20,"Click on the rectangle to change its color");

//Handling the mouse event

rect.setOnMouseClicked(e-

>{ rect.setFill(Color.RED);

});
Group root = new Group (rect,text);

Scene scene = new Scene(root,300,200);

primaryStage.setScene(scene);

primaryStage.setTitle("Mouse Event Demo");

primaryStage.show();

public static void main(String[] args) {

launch(args);

Output

Program Explanation: In above program,

(1) We have created one rectangular object and it is colored using blue color.

(2) The mouse click event is used. When user clicks over the rectangle, the color of the
rectangle gets changed to red.

(3) Mouse Event is created and handled using following code

rect.setOnMouseClicked(e->{
rect.setFill(Color.RED);

});

Keyboard Events

When any key on the keyboard is pressed, released, or typed on a node then the keyboard
event occurs.

The associated keyboard event triggering actions made by user, type of event and event
registration methods are enlisted in the following table.

For recognizing the keyboard events we use KeyEvent class. Various methods of KeyEvent
class are as described in the following table.

The key codes returned by the getCode() method are constants. These constants are enlisted
in the following table -
Following is a simple keyboard event handling program that displays the character typed on
the output window.

Programming Example

package myjavafxapplication;

import javafx.application. Application;

import javafx.event.EventHandler;

import javafx.scene.Group;

import javafx.scene.Scene;

import javafx.scene.input.MouseEvent;

import javafx.scene.text.Font;

import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start(Stage primaryStage) {

Text msg = new Text(20,20,"Type something here...");

Text text = new Text(50,50," ");

text.setFont(Font.font("Arial", FontWeight.BOLD,30));

//Creating the keyboard event handler

text.setOnKeyPressed(e-

>{ text.setText(e.getText());

});

Group root = new Group(msg,text);

Scene scene = new Scene(root, 300,200);

primaryStage.setScene(scene);

primaryStage.setTitle("KeyBord Event Demo");

primaryStage.show();

text.requestFocus();

public static void main(String[] args) {

launch(args);

}
Output

Program Explanation: In above code,

(1) For displaying the character typed we have set the Text node. As we want bold,arial and
a

font size of 30 px, we use setFont method.

(2) Then the keybpard event is set using the lambda function

text.setOnKeyPressed(e->{

text.setText(e.getText());

});

Due to this event, the key being pressed is displayed.

Controls
• The graphical User Interface (GUI) is an essential part of any window based application.

• The interaction between user and the application program is possible with the help of User
Interface (UI) controls that are placed on the screen.

• JavaFX allows its developer a rich set of UI controls. Some of the most commonly used
UI Controls are enlisted in the following table.
Let us now learn and understand how to create simple JavaFX programs that use these UI
controls.

Label
• The label control displays simple text on the screen.

• Its main purpose is to describe other components such as textfield, textarea, radio button
and so on.

• For using this control the package javafx.scene.control.Label need to be imported.

• The constructors used for using Label control is

Label(): This creates an empty label.

Label(String txt): This creates a label with supplied text.

Label(String txt, Node graphics) : It creates a label with supplied text and graphics.

• Programming Example

package MyJavaFXApplication;

import javafx.application.Application;
import static javafx.application.Application.launch;

import javafx.event.ActionEvent;

import javafx.event.EventHandler;

import javafx.scene.Scene;

import javafx.scene.layout.StackPane;

import javafx.scene.control.Label;

import javafx.scene.layout.StackPane;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start (Stage primaryStage)

StackPane root=new StackPane();

Label L=new Label("User Name");

Scene scene = new Scene(root, 250, 250);

root.getChildren().add(L);

primaryStage.setTitle("Label Demo");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);

Output
Program Explanation: In above program,

(1) We have created StackPane so that the Label control can be arranged on top just like a
stack. The stackPane is a used to decide the layout of the screen. This is named as root
node.

(2) Then we have created one label "User Name" using the Label constructor.

(3) These controls must be contained in a scene. Hence a scene is prepared by adding a root
node using Scene constructor. This scene is then attached to a primaryStage using setScene
method.

(4) Then using show() method we display the primaryStage. This ultimately displays the
label control.

Button
• The button control is the most commonly used control in any GUI application. This UI
component controls the behavior of the application. Some event gets generated when a
button is clicked.

• The button control is created using following code

Button btn=new Button("Click Here");

• For using the button control we need to import the package javafx.scene.control.Button.
Following program shows the creation of button control in JavaFX

Programming Example

package MyJavaFXApplication;
import java.io.FileInputStream;

import javafx.application. Application;

import static javafx.application. Application.launch;

import javafx.event.ActionEvent;

import javafx.event.EventHandler;

import javafx.scene.Scene;

import javafx.scene.layout.StackPane;

import javafx.scene.control.Button;

import javafx.scene.layout.StackPane;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start (Stage primaryStage) throws Exception {

StackPane root=new StackPane();

Button B=new Button("Click Me");

Scene scene = new Scene(root, 200, 250);

root.getChildren().add(B);

primaryStage.setTitle("Button Demo");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);

}
Output

Checkbox
Checkbox is used to provide more than one choices at a time.

For using checkbox in our application program, we must insert following line in the program

at the beginning -

import javafx.scene.control.Checkbox

The checkbox can be created using following statement

CheckBox ch=new CheckBox("Label Name");

The checkbox is selected true by using the method, setSelected("true")

Following program shows how to create checkbox.

Programming Example

package MyJavaFXApplication;

import java.io.FileInputStream;

import javafx.application. Application;

import static javafx.application.Application.launch;

import javafx.event.ActionEvent;

import javafx.event.EventHandler;
import javafx.scene.Scene;

import javafx.scene.control.Label;

import javafx.scene.control.CheckBox;

import javafx.scene.layout.HBox;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start (Stage primaryStage)throws Exception

{ HBox root = new HBox();

Label L=new Label("Select your favorite color: ");

CheckBox ch1=new CheckBox("Red");

CheckBox ch2=new CheckBox("Blue");

CheckBox ch3=new CheckBox("Green");

CheckBox ch4=new CheckBox("Yellow");

Scene scene = new Scene(root, 400, 100);

root.getChildren().addAll(L, ch1,ch2,ch3,ch4);

primaryStage.setTitle("Checkbox Demo");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);

Output
ToggleButton
• ToggleButton is a button control that has two states selected or deselected.

• The ToggleButtons are placed in a Toggle Group. From the same group at the most only
one button is selected at a time. If one button is selected from that group then other buttons
of that group remain deselected.

• Constructors

1. ToggleButton(): Creates a toggle button with an empty string for its label.

2. ToggleButton(String txt): Creates a toggle button with the specified text as its label.

Methods

1. setToggleGroup(ToggleGroup val):Sets the value of the property toggleGroup.

2. setSelected(boolean val): Sets the value of the property selected.

3. isSelected(): Gets the value of the property selected.

Example Program

package application;

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.layout.HBox;

import javafx.geometry.Insets;

import javafx.scene.control.Label;

import javafx.scene.control. ToggleButton;

import javafx.scene.control.ToggleGroup;
import javafx.stage.Stage;

public class Main extends Application {

@Override

public void start(Stage primaryStage)throws Exception

{ HBox root=new HBox();

root.setPadding(new Insets(15));

root.setSpacing(10);

root.getChildren().add(new Label("I Like:"));

// Creating a ToggleGroup

ToggleGroup group = new ToggleGroup();

// Creating new Toggle buttons

ToggleButton blueButton = new ToggleButton("Blue");

ToggleButton blackButton = new ToggleButton("Black");

// Set toggle group

blueButton.setToggle Group (group);

blackButton.setToggleGroup(group);

blueButton.setSelected(true);

root.getChildren().addAll(blueButton, blackButton);

Scene scene = new Scene(root, 300, 300);

primaryStage.setTitle("ToggleButton Demo");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);
}

Output

RadioButtons
The Radio button control is used to make a choice.

The difference between checkbox and radio button is that with checkbox we can have more
than one selection but with radio button we select only one option at a time.

We can create a radiobutton as follows-

RadioButton radioButton1 = new RadioButton("Label1");

We can group JavaFX RadioButton instances into a ToggleGroup. A ToggleGroup allows


at most one RadioButton to be selected at any time.

Following example shows how to create and use the radio button control.
Programming Example

package MyJavaFXApplication;

import java.io.FileInputStream;

import javafx.application.Application;

import static javafx.application. Application.launch;

import javafx.event.ActionEvent;

import javafx.event.EventHandler;

import javafx.scene.Scene;

import javafx.scene.control.Label;

import javafx.scene.control.RadioButton;

import javafx.scene.control. ToggleGroup;

import javafx.scene.layout.VBox;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start(Stage primaryStage) throws Exception

{ ToggleGroup group=new ToggleGroup();

Label L=new Label("Select your favorite color: ");

RadioButton rb1=new RadioButton("Red");

RadioButton rb2=new RadioButton("Blue");

RadioButton rb3=new RadioButton("Green");

RadioButton rb4=new RadioButton("Yellow");

rb1.setToggleGroup(group);

rb2.setToggleGroup(group);

rb3.setToggleGroup(group);
rb4.setToggleGroup(group);

VBox root=new VBox();

Scene scene = new Scene(root, 300, 200);

root.getChildren().addAll(L,rb1,rb2,rb3,rb4);

primaryStage.setTitle("RadioButton Demo");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);

Output

Textfield
TextField control allows the user to enter the text that can be read by the application.

The package javafx.scene.control.TextField need to be imported for using the TextField


control.

Programming Example
package MyJavaFXApplication;

import java.io.FileInputStream;

import javafx.application. Application;

import static javafx.application. Application.launch;

import javafx.event.ActionEvent;

import javafx.event.EventHandler;

import javafx.scene.Scene;

import javafx.scene.control.Label;

import javafx.scene.control.TextField;

import javafx.scene.layout.GridPane;

import javafx.scene.layout.VBox;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start(Stage primaryStage)throws Exception

{ Label L=new Label("Enter Name ");

TextField tf=new TextField();

GridPane root=new GridPane();

root.addRow(0,L,tf);

Scene scene = new Scene(root, 300, 200);

primaryStage.setTitle("Text Field Demo");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {


launch(args);

Output

Ex. 5.4.1: Write a JavaFX application for creating a login form.

Sol.:

package MyJavaFXApplication;

import java.io.FileInputStream;

import javafx.application. Application;

import static javafx.application. Application.launch;

import javafx.event.ActionEvent;

import javafx.event.EventHandler;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.control.Label;

import javafx.scene.control.PasswordField;

import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start(Stage primaryStage)throws Exception { Label

L1=new Label("Enter Name ");

TextField tf1-new TextField();

Label L2=new Label("Enter Password ");

TextField tf2 new PasswordField();

Button btn=new Button("Submit");

GridPane root=new GridPane();

root.setVgap(10);

root.addRow(0, L1,tf1)

root.addRow(1, L2,tf2)

root.addRow(2,btn);

Scene scene = new Scene(root, 300, 200);

primaryStage.setTitle("Text Field Demo");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);

Output
TextArea
The TextArea control allows to enter multiline text. This control is represented by the class
javafx.scene.control.TextArea

The textarea control can be created using

TextArea ta= new TextArea()

We can set the size of the TextArea using setPrefHeight() and setPrefWidth() functions.

Following example shows how to create TextArea control

Programming Example

package My JavaFXApplication;

import java.io.FileInputStream;

import javafx.application.Application;

import static javafx.application. Application.launch;

import javafx.event.ActionEvent;

import javafx.event.EventHandler;

import javafx.scene.Scene;

import javafx.scene.control.Label;

import javafx.scene.control.TextArea;

import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start (Stage primaryStage) throws Exception {

Label L=new Label("Enter your Comments: ");

TextArea ta= new TextArea();

double height=100;

double width=150;

ta.setPrefHeight(height);

ta.setPrefWidth(width);

GridPane root=new GridPane();

root.addRow(0,L,ta);

Scene scene = new Scene(root, 300, 200);

primaryStage.setTitle("Text Area Demo");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);

Output
ListView
The JavaFX ListView control enables users to choose one or more options from a
predefined list of choices. The JavaFX ListView control is represented by the class
javafx.scene.control.ListView.

The ListView can be created as follows -

ListView listView = new ListView()

The items can be added to the ListView control using getItems().add() method. For example

listView.getItems().add("Item 1");

listView.getItems().add("Item 2");

……..

To make a ListView visible we have to add it to the scene graph or to some layout
component which is then attached to the Scene object.

Following example program shows how to use ListView Control

Programming Example

package MyJavaFXApplication;

import javafx.application. Application;

import static javafx.application.Application.launch;

import javafx.event.ActionEvent;

import javafx.event.EventHandler;
import javafx.scene.Scene;

import javafx.scene.control.Label;

import javafx.scene.control.ListView;

import javafx.scene.control.SelectionMode;

import javafx.scene.layout.GridPane;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start (Stage primaryStage)throws Exception {

Label L=new Label("Select your favorite programming Language: ");

ListView listView = new ListView();

listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

listView.getItems().add("Java");

listView.getItems().add("C++");

listView.getItems().add("PHP");

listView.getItems().add("Python");

GridPane root=new GridPane();

root.addRow(0,L,listView)

Scene scene = new Scene(root, 350, 200);

primaryStage.setTitle("ListView Demo");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);
}

Output

In above code we have used

listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

which allows multiple selection of items from listview.

ComboBox
We can have predefined list of choices using combo box.

This control is represented by javafx.scene.control.ComboBox class. Hence we need to


import it at the beginning of our application program.

We can create the comboBox using following statement

ComboBox cb=new ComboBox();

Then we need to add the list of choices to the comboBox. This can be done using

cb.getItems().add("Option1")

cb.getItems().add("Option2")

…………..

And so on.
Following program illustrates the use of ComboBox control in the JavaFX application
program.

Programming Example

package MyJavaFXApplication;

import java.io.FileInputStream;

import javafx.application. Application;

import static javafx.application.Application.launch;

import javafx.event.ActionEvent;

import javafx.event.EventHandler;

import javafx.scene.Scene;

import javafx.scene.control.ComboBox;

import javafx.scene.control.Label;

import javafx.scene.layout. GridPane;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start (Stage primaryStage) throws Exception {

Label L=new Label("Select your favorite programming Language: ");

ComboBox cb=new ComboBox();

cb.getItems().add("Java");

cb.getItems().add("C++");

cb.getItems().add("PHP");

cb.getItems().add("Python");

GridPane root = new GridPane();

root.addRow(0,L,cb);
Scene scene = new Scene(root, 350, 200);

primaryStage.setTitle("ComboBox Demo");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);

Output

ChoiceBox
• The ChoiceBox control shows the set of items and allows user to select a single choice. It
will show the currently selected item on the top.

• By default the ChoiceBox control has no selected item. We have to specify the items from
which the choice is to be made.

• For using the ChoiceBox control we need to import javafx.scene.control.ChoiceBox


package

• Constructors of ChoiceBox Class are

ChoiceBox(): It creates empty ChoiceBox


ChoiceBox(ObservableList items): It creates empty ChoiceBox with the given set of items.

Commonly Use Methods are

Programming Example

package application;

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.layout.HBox;

import javafx.geometry.Insets;

import javafx.scene.control.Label;

import javafx.scene.control.ChoiceBox;

import javafx.stage.Stage;

public class Main extends Application {

@Override

public void start (Stage primaryStage) throws Exception {

HBox root=new HBox();

root.setPadding(new Insets(15));

root.setSpacing(10);

// Creating a Label

root.getChildren().add(new Label("My Favorite color is: "));


// Creating a ChoiceBox

ChoiceBox<Object> choiceBox = new ChoiceBox<Object>();

choiceBox.getItems().add("Blue");

choiceBox.getItems().add("Black");

choiceBox.getItems().add("White");

choiceBox.getItems().add("Red");

root.getChildren().add(choiceBox);

Scene scene = new Scene(root, 300, 300);

primaryStage.setTitle("ChoiceBox Demo");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);

Output
Scrollbar
Using the Scrollbar control the user can scroll down to the application page.

For creating this control we use javafx.scene.control.ScrollBar class.

Programming Example

package MyJavaFXApplication;

import javafx.application. Application;

import static javafx.application. Application.launch;

import javafx.scene.Scene;

import javafx.scene.control.Label;

import javafx.scene.control.ScrollBar;

import javafx.scene.layout.StackPane;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

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

ScrollBar sb=new ScrollBar();

StackPane root=new StackPane();

root.getChildren().add(sb);

Copbolwonhot te

Scene scene = new Scene(root, 350, 200);

primaryStage.setTitle("ScrollBar Demo");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);

Output

We can create the scrollbar in horizontal direction or in vertical direction. If we want the
scrollbar to be displayed vertically then we call setOrientation() method
sb.setOrientation (Orientation. VERTICAL);

Similarly we can set minimum, maximum or current value to scrollbar using following
functions

(1) setMin()

(2) setMax()

(3) setValue()

Following program makes use of these methods for the scrollbar control

package MyJavaFXApplication;

import javafx.application. Application;

import static javafx.application.Application.launch;

import javafx.geometry.Orientation;

import javafx.scene.Scene;

import javafx.scene.control.Label;

import javafx.scene.control.ScrollBar;

import javafx.scene.layout.StackPane;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start(Stage primaryStage) throws Exception

{ ScrollBar sb=new ScrollBar();

sb.setMin(0);

sb.setMax(50);

sb.setValue(25);

sb.setOrientation (Orientation. VERTICAL);

StackPane root = new StackPane();


root.getChildren().add(sb);

Scene scene = new Scene(root, 350, 200);

primaryStage.setTitle("ScrollBar Demo");

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

launch(args);

Output

Layouts

• The arrangement of various components (nodes) in a scene within the container is called
Layout of the container.

• For using the layout we must import the package javafx.scene.layout. The class named
Pane is the base class for all the layouts in JavaFX.

• Various layout panes are summarized in the following table.


For adding the nodes to the layout manager follow the following step-

(1) Instantiate the respective layout class. For example

VBox root=new VBox();

(2) Then set the properties of the layout.

For example - if we want the spacing between the created nodes then we use

root.setSpacing(10);

(3) Adding nodes to the layout object, for example -

root.getChildren().addAll(<NodeObjects>);

FlowPane

• A JavaFX FlowPane is a layout component which lays out its child components either
vertically or horizontally, and which can wrap the components onto the next row or column
if there is not enough space in one row.

• The JavaFX Flow Pane layout.FlowPane layout component is represented by the


javafx.scene.layout.FlowPane

• Various methods defined in FlowPane layout are --


• The FlowPane can be created using following syntax

FlowPane flowpane = new FlowPane();

Programming Example

package myjavafxapplication;

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.layout.FlowPane;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start(Stage primaryStage) {

FlowPane root=new FlowPane();

Button B1 = new Button("One");


Button B2 = new Button("Two");

Button B3 = new Button("Three");

Button B4 = new Button("Four");

Button B5 = new Button("Five");

Button B6 = new Button("Six");

root.getChildren().add(B1);

root.getChildren().add(B2);

root.getChildren().add(B3);

root.getChildren().add(B4);

root.getChildren().add(B5);

root.getChildren().add(B6);

Scene scene = new Scene(root, 150, 150);

primaryStage.setScene(scene);

primaryStage.setTitle("FlowPane Demo");

primaryStage.show();

public static void main(String[] args) {

launch(args);

}
HBox

• The HBox layout arranges the children in the form of horizontal rows.

• The HBox class extends Pane class.

• It requires javafx.scene.layout.HBox class which provides all the required methods of this
pane.

• Various methods used for layout using HBox are -

The constructors of HBox class are -

HBox(): Creates an HBox object with no nodes.

HBox(double s): Creates an HBox with spacing in between nodes.

Programming Example

package myjavafxapplication;

import javafx.application. Application;

import javafx.scene.Scene;
import javafx.scene.control.Button;

import javafx.scene.layout.HBox;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start(Stage primaryStage)

{ HBox root=new HBox();

Button B1 = new Button("One");

Button B2 = new Button("Two");

Button B3 = new Button("Three")

Button B4 = new Button("Four");

Button B5 = new Button("Five");

Scene scene = new Scene(root,200,100);

Output

root.getChildren().addAll(B1,B2, B3, B4, B5);

primaryStage.setScene(scene);

primaryStage.setTitle("HBOX Demo");

primaryStage.show();

public static void main(String[] args) {

launch(args);

}
Program Explanation: In above code,

(1) We have created four button elements.

(2) The layout pane is set as HBox. All the button elements are attached to the HBox pane
by using getChildren().addAll function.

(3) This pane is then added to the Scene.

(4) Using setScene method this scene is then added to the PrimaryStage.

VBox

• The VBox layout arranges the children in the form of vertical rows.

• The VBox class extends Pane class.

• It requires javafx.scene.layout.VBox class which provides all the required methods of this
pane.

• Various methods used for layout using VBox are -

• The constructors of VBox class are -

VBox(): Creates an VBox object with no nodes.


VBox(double s): Creates an VBox with spacing in between nodes.

Programming Example

package myjavafxapplication;

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.layout.VBox;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start (Stage primaryStage)

{ VBox root=new VBox();

Button B1 = new Button("One");

Button B2 = new Button("Two");

Button B3 = new Button("Three");

Output

Button B4 = new Button("Four");

Button B5 = new Button("Five");

Scene scene = new Scene(root, 100,150);

root.getChildren().addAll(B1,B2, B3, B4, B5);

primaryStage.setScene(scene);

primaryStage.setTitle("VBOX Demo");

primaryStage.show();
}

public static void main(String[] args) {

launch(args);

BorderPane

• BorderPane lays out children in top, left, right, bottom, and center positions.

• It can be used to create the classic looking application layouts.

• It is represented by javafx.scene.layout.BorderPane class.

• Various methods of BorderPane layout are

• The BorderPane layout is created as follows-

(1) BorderPane(): Creates a new Border Pane.


(2) BorderPane (Node c): Creates a new Border Pane with specified node at center.

(3) BorderPane (Node center, Node top, Node right, Node bottom, Node left): Creates an
BorderPane layout with the given Nodes to use for each of the main layout areas of the
Border Pane.

Programing Example

package myjavafxapplication;

import javafx.application. Application;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.layout.BorderPane;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application

@Override

public void start (Stage primaryStage)

Button'B_top = new Button("One");

Button B center = new Button("Two");

Button B_bottom= new Button("Three");

Button B_left = new Button("Four");

Output

Button B_right = new Button("Five");

BorderPane root = new BorderPane();

root.setTop(B_top);
root.setCenter(B_center);

root.setBottom (B_bottom);

root.setLeft(B_left);

root.setRight (B_right);

Scene scene = new Scene(root,250,250);

primaryStage.setScene(scene);

primaryStage.setTitle("Border Pane Demo");

primaryStage.show();

public static void main(String[] args) {

launch(args);

StackPane
• StackPane is a layout in which every new node is placed on the top of previous node.

• It makes use of javafx.scene.layout.StackPane class.

• Various methods of StackPane layout are -

• The constructor for StackPane layout is

1. StackPane()

2. StackPane (Node... Children)

Programming Example

package myjavafxapplication;

import javafx.application. Application;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.layout.StackPane;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override

public void start(Stage primaryStage)

{ StackPane root=new StackPane();

Button B1 = new Button("This button is with caption One");


Button B2 = new Button("Two is on its top");

Button B3 = new Button("Three");

Scene scene=new Scene(root,100,150);

Output

root.getChildren().addAll(B1,B2,B3);

primaryStage.setScene(scene);

primaryStage.setTitle("StackPane Demo");

primaryStage.show();

public static void main(String[] args) {

launch(args);

GridPane

GridPane places its nodes into a grid of rows and columns. Nodes may span multiple rows
or columns. GridPane is the most flexible built-in layout pane.

The GridPane is given by


Various methods used in GridPane are -

GridPane gridPane = new GridPane();

Following example shows the use of GridPane layout

Programming Example

package myjavafxapplication;

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.layout.GridPane;

import javafx.stage.Stage;

public class MyJavaFXApplication extends Application {

@Override
public void start(Stage primaryStage) {

GridPane grid=new GridPane();

Button B1 = new Button("One");

Button B2 = new Button("Two");

Button B3 = new Button("Three");

Button B4 = new Button("Four");

Button B5 = new Button("Five");

Button B6 = new Button("Six");

grid.add(B1,0,0);

grid.add(B2,1,0);

grid.add(B3,2,0);

grid.add(B4,0,1);

grid.add(B5,1,1);

Output

grid.add(B6,2,1);

Scene scene=new Scene(grid, 150, 150);

primaryStage.setScene(scene);

primaryStage.setTitle("GridPane Demo");

primaryStage.show();

public static void main(String[] args) {

launch(args);

}
}

Menu

• In JavaFX we can create a menu using a Menu class.

• For using the Menu class in our JavaFX application we need to import
javafx.scene.control. Menu so that the methods associated with this class can be used in the
application.

• Menu is a popup menu that contains several menu items that are displayed when the user
clicks a menu. The user can select a menu item from the menu.

• Constructors for Menu class are

• Commonly used Methods are

Menu Bars
• MenuBar is just like a navigation bar with menus on it. The menubar is located at the the
screen.

• The MenuBar class is available javafx.scene.control.MenuBar package.

• Constructors for MenuBar class are

Menultem

• A MenuItem is a basic item that goes on a menu.

• Following Fig. 5.6.1 shows the menu,menubar and menuitems.

Steps for creating JavaFX application for creating Menu

Step 1: Create a Menu bar is the first step, MenuBar can be instantiated using new

MenuBar menuBar = new MenuBar();


Step 2: Now create the menu. The name of the menu is passed as an argument to the Menu
class.

Menu fileMenu = new Menu("File");

Step 3: Create the menuitem. The name of the menu is passed as an argument to the
MenuItem class.

MenuItem newItem = new MenuItem("New");

Step 4: Add menu items to the menu using add or addAll method

fileMenu.getItems().addAll(newItem, openFileItem, saveltem, exitItem);

Step 5: Add Menu to Menu Bar using add or addAll method.

menuBar.getMenus().addAll(file Menu, editMenu, aboutMenu);

Programming Example

package application;

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Menu;

import javafx.scene.control.MenuBar;

import javafx.scene.control.MenuItem;

import javafx.scene.layout.BorderPane;

import javafx.stage.Stage;

public class Main extends Application {

@Override

public void start (Stage stage) {

// Creating MenuBar

MenuBar menuBar = new MenuBar();


// Creating three menus

Menu file Menu = new Menu("File");

Menu editMenu = new Menu("Edit");

Menu aboutMenu = new Menu("About");

// Creating MenuItems for File menu

MenuItem newItem = new MenuItem("New");

MenuItem openFileItem = new MenuItem("Open File");

MenuItem saveItem = new MenuItem("Save");

MenuItem exitItem = new MenuItem("Exit");

// Creating MenuItems for Edit menu

MenuItem cutItem = new MenuItem("Cut");

MenuItem copyItem = new MenuItem("Copy");

MenuItem pasteItem = new MenuItem("Paste");

//There is no menu item for About menu

//Now Adding menuItems to the Menus

fileMenu.getItems().addAll(newItem, openFileItem, saveItem, exitItem);

editMenu.getItems().addAll(cutItem,copyItem, pasteItem);

//Adding Menus to the MenuBar

menuBar.getMenus().addAll(fileMenu, editMenu, aboutMenu);

BorderPane root = new BorderPane();

root.setTop(menuBar);

Scene scene = new Scene(root, 400, 300);

stage.setTitle("JavaFX Menu Demo");


stage.setScene(scene);

stage.show();

public static void main(String[] args) {

Application.launch(args);

Output

You might also like