Javafx

Download as pdf or txt
Download as pdf or txt
You are on page 1of 73

JAVA FX

JavaFX Basic Concepts


• JavaFX is lightweight.
• From a programmer’s point of view, the first differences you notice between
JavaFX and Swing are the organization of the framework and the
relationship of the main components.
• JavaFX offers a more streamlined, easier-to-use, updated approach. JavaFX
also greatly simplifies the rendering of objects because it handles repainting
automatically. It is no longer necessary for your program to handle this task
manually.
• The preceding is not intended to imply that Swing is poorly designed. It is
not. It is just that the art and science of programming has moved forward,
and JavaFX has received the benefits of that evolution.
• Simply put, JavaFX facilitates a more visually dynamic approach to GUIs
The JavaFX Packages
• The JavaFX elements are contained in packages that begin with the
javafx prefix.
• At the time of this writing, there are more than 30 JavaFX packages in
its API library.
• Here are four examples: javafx.application, javafx.stage, javafx.scene,
and javafx.scene.layout.
• Although we will only use a few of these packages.
• JavaFX offers a wide array of functionality
The Stage and Scene Classes
• The central metaphor implemented by JavaFX is the stage.
• As in the case of an actual stage play, a stage contains a scene.
• Thus, loosely speaking, a stage defines a space and a scene defines what
goes in that space. Or, put another way, a stage is a container for scenes and
a scene is a container for the items that comprise the scene.
• As a result, all JavaFX applications have at least one stage and one scene.
• These elements are encapsulated in the JavaFX API by the Stage and Scene
classes.
• To create a JavaFX application, you will, at minimum, add at least one
Scene object to a Stage.
Cont..
• .Let’s look a bit more closely at these two classes.
• Stage is a top-level container.
• All JavaFX applications automatically have access to one Stage,
called the primary stage.
• The primary stage is supplied by the run-time system when a JavaFX
application is started.
• Although you can create other stages, for many applications, the
primary stage will be the only one required
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.
• public void init()
• public abstract void start(Stage primaryStage)
• public void stop()
Cont..
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 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.
package application;
import javafx.application.Application;
import javafx.stage.Stage;
public class Hello_World extends Application{

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
}
}
Cont..
• 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.
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.

Nodes and Scene Graphs
• Nodes and Scene Graphs :The individual elements of a scene are called nodes.
• For example, a push button control is a node. However, nodes can also consist of groups
of nodes. Furthermore, a node can have a child node. In this case, a node with a child is
called a parent node or branch node.
• Nodes without children are terminal nodes and are called leaves.
• The collection of all nodes in a scene creates what is referred to as a scene graph, which
comprises a tree. There is one special type of node in the scene graph, called the root
node.
• This is the top-level node and is the only node in the scene graph that does not have a
parent.
• Thus, with the exception of the root node, all other nodes have parents, and all nodes
either directly or indirectly descend from the root node.
• The base class for all nodes is Node. There are several other classes that are, either
directly or indirectly, subclasses of Node. These include Parent, Group, Region, and
Control.
Layouts JavaFX
• Layouts JavaFX provides several layout panes that manage the process
of placing elements in a scene.
• For example, the FlowPane class provides a flow layout and the
GridPane class supports a row/column grid-based layout.
• Several other layouts, such as BorderPane (which is similar to the
AWT’s BorderLayout), are available.
• The layout panes are packaged in javafx.scene.layout.
package application;
import javafx.application.Application;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.scene.layout.StackPane;
public class Hello_World extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Button btn1=new Button("Say, Hello World");
StackPane root=new StackPane();
root.getChildren().add(btn1);
} }
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.scene.layout.StackPane;
public class Hello_World extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Button btn1=new Button("Say, Hello World");
StackPane root=new StackPane();
root.getChildren().add(btn1);
Scene scene=new Scene(root); } }
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.scene.layout.StackPane;
public class Hello_World extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Button btn1=new Button("Say, Hello World");
StackPane root=new StackPane();
root.getChildren().add(btn1);
Scene scene=new Scene(root);
primaryStage.setScene(scene);
primaryStage.setTitle("First JavaFX Application");
primaryStage.show(); }
}
package application;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.scene.layout.StackPane;
public class Hello_World extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
//
TODO Auto-generated method stub
Button btn1=new Button("Say, Hello World");
btn1.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("hello world");
}
} );

StackPane root=new StackPane();


root.getChildren().add(btn1);
Scene scene=new Scene(root,600,400);
primaryStage.setTitle("First JavaFX Application");
primaryStage.setScene(scene);
primaryStage.show();
}
publicstaticvoid main (String[] args)
{
launch(args);
}
}
The Application Class and the Life-cycle
Methods
• A JavaFX application must be a subclass of the Application class, which is
packaged in javafx.application.
• Thus, your application class will extend Application.
• The Application class defines three life-cycle methods that your application
can override.
• These are called init( ), start( ), and stop( ), and are shown here, in the order
in which they are called:
• void init( ) abstract
• void start(Stage primaryStage)
• void stop( )
• The init( ) method is called when the application begins execution. It
is used to perform various initializations.
• However, it cannot be used to create a stage or build a scene. If no
initializations are required, this method need not be overridden
because an empty, default version is provided.
• The start( ) method is called after init( ). This is where your application
begins and it can be used to construct and set the scene.
• Notice that it is passed a reference to a Stage object.
• This is the stage provided by the run-time system and is the primary
stage. (You can also create other stages, but you won’t need to for
simple applications.) Notice that this method is abstract. Thus, it must
be overridden by your application.
• When your application is terminated, the stop( ) method is called. It is here that
you can handle any cleanup or shutdown chores. In cases in which no such actions
are needed, an empty, default version is provided.
• To start a free-standing JavaFX application, you must call the launch( ) method
defined by Application.
• It has two forms. Here is the one used in this chapter:
• public static void launch(String ... args)
• Here, args is a possibly empty list of strings that typically specify command-line
arguments.
• When called, launch( ) causes the application to be constructed, followed by calls
to init( ) and start( ). The launch( ) method will not return until after the
application has terminated.
• This version of launch( ) starts the subclass of Application from which launch( ) is
called.
A JavaFX Application Skeleton

// A JavaFX application skeleton.


import javafx.application.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.layout.*;
public class JavaFXSkel extends Application {

public static void main(String[] args)


{
System.out.println("Launching JavaFX application."); // Start the JavaFX
//application by calling launch().
launch(args);
}
// Override the init() method.
public void init()
{
System.out.println("Inside the init() method.");
}

// Override the start() method.


public void start(Stage myStage) {
System.out.println("Inside the start() method.");
// Give the stage a title.
myStage.setTitle("JavaFX Skeleton.");
// Createa root node. In this case, a flow layout pane
// is used, but several alternatives exist.
FlowPane rootNode = new FlowPane()

// Create a scene.
Scene myScene = new Scene(rootNode, 300, 200);
// Set the scene on the stage.
myStage.setScene(myScene);
// Show the stage and its scene.
myStage.show();
}
// Override the stop() method.
public void stop() {
System.out.println("Inside the stop() method.");
}
}
A Simple JavaFX Control: Label
• The JavaFX label is an instance of the Label class, which is packaged
in javafx.scene.control.
• Label inherits Labeled and Control, among other classes.
• The Labeled class defines several features that are common to all
labeled elements (that is, those that can contain text), and Control
defines features related to all controls.
• Label defines three constructors. The one we will use here is
Label(String str) Here, str is the string that is displayed.
Using Buttons and Events
• One commonly used control is the button.
• This makes button events one of the most frequently handled.
• Button is a good way to demonstrate the fundamentals of event
handling in JavaFX. For this reason, the fundamentals of event
handling and the button are introduced together.
Event Basics
• The base class for JavaFX events is the Event class, which is packaged in
javafx.event.
• Event inherits java.util.EventObject, which means that JavaFX events share the
same basic functionality as other Java events.
• Several subclasses of Event are defined. The one that we will use here is
ActionEvent.
• It handles action events generated by a button. In general, JavaFX uses what is, in
essence, the delegation event model approach to event handling.
• To handle an event, you must first register the handler that acts as a listener for
the event.
• When the event occurs, the listener is called. It must then respond to the event and
return.
• Events are handled by implementing the EventHandler interface, which is also in
javafx.event.
Cont..
Introducing the Button Control
• In JavaFX, the push button control is provided by the Button class,
which is in javafx.scene.- control. Button inherits a fairly long list of
base classes that include ButtonBase, Labeled, Region, Control,
Parent, and Node.
Button defines three constructors.
Button(String str)
In this case, str is the message that is displayed in the button.
When a button is pressed, an ActionEvent is generated.
ActionEvent is packaged in javafx.event.
You can register a listener for this event by using setOnAction( ), which has this
general form:
final void setOnAction(EventHandler handler)
Here, handler is the handler being registered.

The setOnAction( ) method sets the property onAction, which stores a reference to
the handler.
As with all other Java event handling, your handler must respond to the event as fast
as possible and then return. If your handler consumes too much time, it will
noticeably slow down the application. For lengthy operations, you must use a
separate thread of execution.
Drawing Directly on a Canvas
• This is one of the most important ways that JavaFX improves on
Swing. As you may know, in Swing or the AWT, you must call the
repaint( ) method to cause a window to be repainted. Furthermore,
your application needs to store the window contents, redrawing them
when painting is requested. JavaFX eliminates this tedious mechanism
because it keeps track of what you display in a scene and redisplays
that scene as needed. This is called retained mode. With this approach,
there is no need to call a method like repaint( ). Rendering is
automatic.
Exploring JavaFX Controls
• The JavaFX control classes discussed in this chapter are shown here:
• Button
• ListView
• TextField
• CheckBox
• RadioButton
• ToggleButton
• Label
• ScrollPane
• TreeView
• These and the other JavaFX controls are packaged in javafx.scene.control.
IMAGES
• At the foundation for JavaFX’s support for images are two classes:
• Image and ImageView.
• Image encapsulates the image, itself
• ImageView manages the display of an image.
• Both classes are packaged in javafx.scene.image
Cont..
• The Image class loads an image from either an InputStream, a URL, or a path to
the image file.
• Image defines several constructors; this is the one we will use: Image(String url)
• Here, url specifies a URL or a path to a file that supplies the image.
• Once you have an Image, you will use ImageView to display it.
• ImageView is derived from Node, which means that it can be part of a scene
graph.
• ImageView defines three constructors.
• The first one we will use is shown here:
• ImageView(Image image)
• This constructor creates an ImageView that uses image for its image.
In the program, pay close attention to the following sequence that
loads the image and then creates an ImageView that uses that
image:
// Create an image.
Image hourglass = new Image("HourGlass.png");
// Create an image view that uses the image.
ImageView hourglassIV = new ImageView(hourglass);
Excercise
• Adding an Image to a Label
• Using an Image with a Button
ToggleButton
• A useful variation on the push button is called the toggle button.
• A toggle button looks just like a push button, but it acts differently because it has two states:
pushed and released.
• That is, when you press a toggle button, it stays pressed rather than popping back up as a regular
push button does.
• When you press the toggle button a second time, it releases (pops up). Therefore, each time a
toggle button is pushed, it toggles between these two states.
• In JavaFX, a toggle button is encapsulated in the ToggleButton class.
• It implements the Toggle interface, which defines functionality common to all types of two-state
buttons. ToggleButton defines three constructors.
• ToggleButton(String str) Here, str is the text displayed in the button. Another constructor allows
you to include an image. Like other buttons, a ToggleButton generates an action event when it is
pressed. Because ToggleButton defines a two-state control, it is commonly used to let the user
select an option
Cont..
• To do this, use the isSelected( ) method, shown here:
• final boolean isSelected( )
• It returns true if the button is pressed and false otherwise
RadioButton
• Another type of button provided by JavaFX is the radio button.
• Radio buttons are a group of mutually exclusive buttons, in which only one button
can be selected at any one time.
• They are supported by the RadioButton class, which extends both ButtonBase and
ToggleButton.
• It also implements the Toggle interface.
• Thus, a radio button is a specialized form of a toggle button. You have almost
certainly seen radio buttons in action because they are the primary control
employed when the user must select only one option among several alternatives.
• To create a radio button, we will use the following constructor:
• RadioButton(String str)
• Here, str is the label for the button. Like other buttons, when a RadioButton is
used, an action event is generated
CheckBox
• The CheckBox class encapsulates the functionality of a check box.
• Its immediate superclass is ButtonBase.
• Although you are no doubt familiar with check boxes because they are widely used controls, the
JavaFX check box is a bit more sophisticated than you may at first think. This is because
CheckBox supports three states.
• The first two are checked or unchecked, as you would expect, and this is the default behavior.
• The third state is indeterminate (also called undefined). It is typically used to indicate that the state
of the check box has not been set or that it is not relevant to a specific situation. If you need the
indeterminate state, you will need to explicitly enable it.
• CheckBox defines two constructors. The first is the default constructor. The second lets you
specify a string that identifies the box.
• It is shown here: CheckBox(String str) It creates a check box that has the text specified by str as a
label. As with other buttons, a CheckBox generates an action event when it is selected
ListView
• Another commonly used control is the list view, which in JavaFX is encapsulated by
ListView.
• List views are controls that display a list of entries from which you can select one or
more.
• Because of their ability to make efficient use of limited screen space, list views are
popular alternatives to other types of selection controls.
• ListView is a generic class that is declared like this: class ListView<T>
• Here, T specifies the type of entries stored in the list view.
• Often, these are entries of type String, but other types are also allowed.
• ListView defines two constructors. The first is the default constructor, which creates an
empty ListView.
• The second lets you specify the list of entries in the list.
• It is shown here: ListView(ObservableList list) Here, list specifies a list of the items that
will be displayed.
• It is an object of type ObservableList, which defines a list of observable objects. It
inherits java.util.List.
// Demonstrate a list view.
import javafx.application.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;
import javafx.beans.value.*;
import javafx.collections.*;
public class ListViewDemo extends Application {
Label response;
ComboBoX
• A control related to the list view is the combo box, which is implemented in
JavaFX by the ComboBox class.
• A combo box displays one selection, but it will also display a drop-down list that
allows the user to select a different item.
• You can also allow the user to edit a selection. ComboBox inherits
ComboBoxBase, which provides much of its functionality.
• Unlike the ListView, which can allow multiple selections, ComboBox is designed
for single-selection. ComboBox is a generic class that is declared like this:
class ComboBox<T>
Here, T specifies the type of entries.
Often, these are entries of type String, but other types are also allowed.
• ComboBox defines two constructors. The first is the default
constructor, which creates an empty ComboBox.
• The second lets you specify the list of entries. It is shown here:
• ComboBox(ObservableList<T> list)
• In this case, list specifies a list of the items that will be displayed. It is
an object of type ObservableList, which defines a list of observable
objects.
END

You might also like