0% found this document useful (0 votes)
28 views

Java - Programming Module5 (JavaFX)

Uploaded by

sanjayyalla4661
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Java - Programming Module5 (JavaFX)

Uploaded by

sanjayyalla4661
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

MODULE-V Applets, Event Handling

5.1 JavaFXBasicConcepts
JavaFX is a Java library that is 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.
Our JavaFX tutorial includes all topics of JavaFX library such as Fundamentals, 2D Shapes,
3D Shapes, Effects, Animation, Text, Layouts, UI Controls, Transformations, Charts, JavaFX
with CSS, JavaFX with Media etc.
5.1.1 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.
5.1.2 History of JavaFX
JavaFX was developed by Chris Oliver. Initially the project was named as Form Follows
Functions (F3) . It is intended to provide the richer functionalities for the GUI application
development. Later, Sun Micro-systems acquired F3 project as JavaFX in June, 2005.
Sun Micro-systems announces it officially in 2007 at W3 Conference. In October 2008,
JavaFX 1.0 was released. In 2009, ORACLE corporation acquires Sun Micro-Systems and
released JavaFX 1.2. the latest version of JavaFX is JavaFX 1.8 which was released on 18th
March 2014.
5.1.3 Features of JavaFX
Feature Description

Java Library It is a Java library which consists of many classes and


interfaces that are written in Java.

FXML FXML is the XML based Declarative mark up language.


The coding can be done in FXML to provide the more
enhanced GUI to the user.

Scene Builder Scene Builder generates FXML mark-up which can be


ported to an IDE.

Web view Web pages can be embedded with JavaFX applications.


Web View uses WebKitHTML technology to embed web
pages.

Built in UI controls JavaFX contains Built-in components which are not


dependent on operating system. The UI component are just
enough to develop a full featured application.

CSS like styling JavaFX code can be embedded with the CSS to improve the
style of the application. We can enhance the view of our
application with the simple knowledge of CSS.
Swing interoperability The JavaFX applications can be embedded with swing code
using the Swing Node class. We can update the existing
swing application with the powerful features of JavaFX.

Canvas API Canvas API provides the methods for drawing directly in
an area of a JavaFX scene.

Rich Set of APIs JavaFX provides a rich set of API's to develop GUI
applications.

Integrated Graphics An integrated set of classes are provided to deal with 2D


Library and 3D graphics.

Graphics Pipeline JavaFX graphics are based on Graphics rendered


pipeline(prism). It offers smooth graphics which are
hardware accelerated.

High Performance The media pipeline supports the playback of web


Media Engine multimedia on a low latency. It is based on a Gstreamer
Multimedia framework.

Self-contained Self Contained application packages have all of the


application deployment application resources and a private copy of Java and
model JavaFX Runtime.

5.2 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 javafx.scene.layout package. javafx.scene.layout.Pane class is the
base class for all the built-in layout classes in JavaFX.
Layout Classes
javafx.scene.layout 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, root.setSpacing(20);
3. Adding nodes to the layout object, for example,
root.getChildren().addAll(<NodeObjects>);

5.3 JavaFX Application Structure


JavaFX application is divided hierarchically into three main components known as Stage,
Scene and nodes. We need to import javafx.application.Application 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 javafx.application.Application 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.
Javafx.scene.Scene 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 javafx.scene 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 javafx.scene package therefore we need to import the
package into our application in order to create a full featured javafx application.

5.4 JavaFX UI Controls


This part of the tutorial provides you the in-depth knowledge of 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 javafx.scene.control 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. javafx.scene.control.TextField
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
javafx.scene.control.HyperLink

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
javafx.scene.control.ProgressBar.

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.
5.5 JavaFX Label
javafx.scene.control.Label 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: javafx.scene.control
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 graphics
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class LabelTest extends Application {


@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Label my_label=new Label("This is an example of Label");
StackPane root = new StackPane();
Scene scene=new Scene(root,300,300);
root.getChildren().add(my_label);
primaryStage.setScene(scene);
primaryStage.setTitle("Label Class Example");
primaryStage.show();

}
public static void main(String[] args) {
launch(args);
}
}
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.
import java.io.FileInputStream;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class LabelTest extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
StackPane root = new StackPane();
FileInputStream input= new
FileInputStream("/home/javatpoint/Desktop/JavaFX/Images/colored_label.png");
Image image = new Image(input);
ImageView imageview=new ImageView(image);
Label my_label=new Label("Home",imageview);
Scene scene=new Scene(root,300,300);
root.getChildren().add(my_label);
primaryStage.setScene(scene);
primaryStage.setTitle("Label Class Example");
primaryStage.show();

}
public static void main(String[] args) {
launch(args);
}
}
Output:
5.6 JavaFX Button
JavaFX button control is represented by javafx.scene.control.Button 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.
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.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ButtonTest extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub

StackPane root = new StackPane();


Button btn=new Button("This is a button");
Scene scene=new Scene(root,300,300);
root.getChildren().add(btn);
primaryStage.setScene(scene);
primaryStage.setTitle("Button Class Example");
primaryStage.show();

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

Output:
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.
import java.io.FileInputStream;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ButtonTest extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub

FileInputStream input=new
FileInputStream("/home/javatpoint/Desktop/JavaFX/Images/colored_label.png
");
Image image = new Image(input);
ImageView img=new ImageView(image);

StackPane root = new StackPane();


Button btn=new Button("Button 1",img);
btn.setWrapText(true);
Scene scene=new Scene(root,300,300);
root.getChildren().add(btn);
primaryStage.setScene(scene);
primaryStage.setTitle("Button Class Example");
primaryStage.show();

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

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.

import java.io.FileInputStream;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ButtonTest extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub

FileInputStream input=new
FileInputStream("/home/javatpoint/Desktop/JavaFX/Images/colored_label.png");
Image image = new Image(input);
ImageView img=new ImageView(image);

StackPane root = new StackPane();


Button btn=new Button();
btn.setGraphic(img);
btn.setWrapText(true);
Scene scene=new Scene(root,300,300);
root.getChildren().add(btn);
primaryStage.setScene(scene);
primaryStage.setTitle("Button Class Example");
primaryStage.show();

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

5.7 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.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class RadioButtonTest extends Application {

public static void main(String[] args) {


launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
ToggleGroup group = new ToggleGroup();
RadioButton button1 = new RadioButton("option 1");
RadioButton button2 = new RadioButton("option 2");
RadioButton button3 = new RadioButton("option 3");
RadioButton button4 = new RadioButton("option 4");
button1.setToggleGroup(group);
button2.setToggleGroup(group);
button3.setToggleGroup(group);
button4.setToggleGroup(group);
VBox root=new VBox();
root.setSpacing(10);
root.getChildren().addAll(button1,button2,button3,button4);
Scene scene=new Scene(root,400,300);
primaryStage.setScene(scene);
primaryStage.setTitle("Radio Button Example");
primaryStage.show();
}
}
Output:

5.8 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 javafx.scene.control.CheckBox class to implement CheckBox.
Use the following line in the code to create a blank CheckBox.
CheckBox checkbox = new CheckBox();

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


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.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class CheckBoxTest extends Application {

public static void main(String[] args) {


launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Label l = new Label("What do you listen: ");
CheckBox c1 = new CheckBox("Radio one");
CheckBox c2 = new CheckBox("Radio Mirchi");
CheckBox c3 = new CheckBox("Red FM");
CheckBox c4 = new CheckBox("FM GOLD");
HBox root = new HBox();
root.getChildren().addAll(l,c1,c2,c3,c4);
root.setSpacing(5);
Scene scene=new Scene(root,800,200);
primaryStage.setScene(scene);
primaryStage.setTitle("CheckBox Example");
primaryStage.show();
}
}
Output:
5.9 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 . This JavaFX ListView tutorial will explain how to use the
ListView class.
Creating a ListView
You create a ListView simply by creating a new instance of the ListView class. Here is a
JavaFX ListView instantiation example:
ListView listView = new ListView();
Adding Items to a ListView
You can add items (options) to a ListView by obtaining its item collection and add items to it.
Here is an example that adds items to a JavaFX ListView :
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
Adding a ListView to the Scene Graph
To make a ListView visible you must add it to the scene graph. This means that you must add
the ListView to a Scene object or to some layout component which is then attached to the
Scene object.
Here is an example showing how to add a JavaFX ListView to the scene graph:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class ListViewExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ListView Experiment 1");
ListView listView = new ListView();
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
HBox hbox = new HBox(listView);
Scene scene = new Scene(hbox, 300, 120);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Output:

5.10 ComboBox
The JavaFX ComboBox control enables users to choose an option from a predefined list of
choices, or type in another value if none of the predefined choices matches what the user want
to select. The JavaFX ComboBox control is represented by the class
javafx.scene.control.ComboBox . This JavaFX ComboBox tutorial will explain how to use the
ComboBox class.
Creating a ComboBox
You create a ComboBox simply by creating a new instance of the ComboBox class. Here is a
JavaFX ComboBox instantiation example:
ComboBox comboBox = new ComboBox();
Adding Choices to a ComboBox
You can add choices to a ComboBox by obtaining its item collection and add items to it. Here
is an example that adds choices to a JavaFX ComboBox :
comboBox.getItems().add("Choice 1");
comboBox.getItems().add("Choice 2");
comboBox.getItems().add("Choice 3");
Adding a ComboBox to the Scene Graph
To make a ComboBox visible you must add it to the scene graph. This means that you must
add the ComboBox to a Scene object or to some layout component which is then attached to
the Scene object.
Here is an example showing how to add a JavaFX ComboBox to the scene graph:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class ComboBoxExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ComboBox Experiment 1");
ComboBox comboBox = new ComboBox();
comboBox.getItems().add("Choice 1");
comboBox.getItems().add("Choice 2");
comboBox.getItems().add("Choice 3");
HBox hbox = new HBox(comboBox);
Scene scene = new Scene(hbox, 200, 120);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}

5.11 JavaFX TextField


Text Field is basically used to get the input from the user in the form of text.
javafx.scene.control.TextField 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.
import javafx.application.Application;
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 PasswordFieldTest extends Application {

public static void main(String[] args) {


launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Label user_id=new Label("User ID");
Label password = new Label("Password");
TextField tf=new TextField();
PasswordField pf=new PasswordField();
pf.setPromptText("Enter Password");
Button b = new Button("Submit");
GridPane root = new GridPane();
root.addRow(0, user_id, tf);
root.addRow(1, password, pf);
root.addRow(5, b);
Scene scene=new Scene(root,300,200);
primaryStage.setScene(scene);
primaryStage.setTitle("PasswordField Example");
primaryStage.show();
}
}

Output:

5.12 JavaFX ScrollBar


JavaFX Scroll Bar is used to provide a scroll bar to the user so that the user can scroll down
the application pages. It can be created by instantiating javafx.scene.control.ScrollBar class.
The following code implements scrollbar into our application.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ScrollBar extends Application{

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
ScrollBar s = new ScrollBar();
StackPane root = new StackPane();
root.getChildren().add(s);
Scene scene = new Scene(root,300,200);
primaryStage.setScene(scene);
primaryStage.setTitle("ScrollBar Example");
primaryStage.show();

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

Output:
Setting values and orientation
As we see in the modern days application, the scrollbar is shown horizontally as well as
vertically. In JavaFX, we can set any of the orientation for the scrollbar. setOrientation() and
passing the Orientation.VERTICAL property into the method as an argument.
ScrollBar class also provide three methods named as:
1. setMin()
2. setMax()
3. setValue()
these methods are used to set the minimum, maximum and current value of the scrollbar. It
decides span of the scrollbar. The following code shows the implementation.
import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Progress_Indicator extends Application{

@Override
publicvoid start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
ScrollBar s = new ScrollBar();
s.setMin(0);
s.setMax(200);
s.setValue(110);
s.setOrientation(Orientation.VERTICAL);
s.setUnitIncrement(12);
s.setBlockIncrement(10);
StackPane root = new StackPane();
root.getChildren().add(s);
Scene scene = new Scene(root,300,200);
primaryStage.setScene(scene);
primaryStage.setTitle("ScrollBar Example");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}

}
Output:

5.13 JavaFX Menu


JavaFX provides a Menu class to implement menus. Menu is the main component of a any
application. In JavaFX, javafx.scene.control.Menu 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. MenuName.getItems().add(MenuItem1); //adding Menu Item to the Menu
5. menubar.getMenus().add(MenuName); //adding Menu to the MenuBar

EXAMPLE:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MenuExample extends Application {
public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
BorderPane root = new BorderPane();
Scene scene = new Scene(root,200,300);
MenuBar menubar = new MenuBar();
Menu FileMenu = new Menu("File");
MenuItem filemenu1=new MenuItem("new");
MenuItem filemenu2=new MenuItem("Save");
MenuItem filemenu3=new MenuItem("Exit");
Menu EditMenu=new Menu("Edit");
MenuItem EditMenu1=new MenuItem("Cut");
MenuItem EditMenu2=new MenuItem("Copy");
MenuItem EditMenu3=new MenuItem("Paste");
EditMenu.getItems().addAll(EditMenu1,EditMenu2,EditMenu3);
root.setTop(menubar);
FileMenu.getItems().addAll(filemenu1,filemenu2,filemenu3);
menubar.getMenus().addAll(FileMenu,EditMenu);
primaryStage.setScene(scene);
primaryStage.show();

}
}

Output:

5.14 Event Handling in JavaFX


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.
We can also pass lambda expressions to handle the events. The following code implements the
Button event.
import java.io.FileInputStream;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class LabelTest extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub

FileInputStream input=new
FileInputStream("/home/javatpoint/Desktop/JavaFX/Images/colored_label.png");
Image image = new Image(input);
ImageView img=new ImageView(image);

StackPane root = new StackPane();


Button btn=new Button();
btn.setGraphic(img);
btn.setWrapText(true);
btn.setOnAction(new EventHandler<ActionEvent>() {

@Override
publicvoid handle(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Button clicked");

}
} );

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


root.getChildren().add(btn);
primaryStage.setScene(scene);
primaryStage.setTitle("Button Class Example");
primaryStage.show();

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

You might also like