Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Lesson 9 GUI in Java

This document provides an overview of creating Graphical User Interfaces (GUIs) in Java using two main APIs: Swing and JavaFX. It details the components, development processes, and event-driven programming concepts in JavaFX, including the use of Scene Builder for designing GUIs. Additionally, it covers specific components like RadioButtons, CheckBoxes, and ImageView, along with their implementation and event handling in Java applications.

Uploaded by

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

Lesson 9 GUI in Java

This document provides an overview of creating Graphical User Interfaces (GUIs) in Java using two main APIs: Swing and JavaFX. It details the components, development processes, and event-driven programming concepts in JavaFX, including the use of Scene Builder for designing GUIs. Additionally, it covers specific components like RadioButtons, CheckBoxes, and ImageView, along with their implementation and event handling in Java applications.

Uploaded by

kalkidanasale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Creating GUI in Java

Slides in this presentation contain hyperlinks.


JAWS users should be able to get a list of links by
using INSERT+F7
Graphical User Interface (GUI) in Java
There are two APIs to create GUI in java.
1. Swing
2. Java FX

This table compares the two APIs.


Basis Of
Java Swing Java FX
Comparison
Swing has a number of components Less component as compared to legacy
Components
to it Swing APIs
Standard UI components can be Rich GUI components can be created
User interface
designed with Swing with advanced look and feel
Swing APIs are being used to write JavaFX scripts and fast UI development
Development
UI components with screen builder
No new functionality introduction for JavaFX has a rich new toolkit, expected
Functionality
future to grow in future
Up and coming to feature rich UI
Category Legacy UI library fully featured
components
MVC support across components
MVC support Friendly with MVC pattern
lack consistency

educba.com
Chapter 15

Creating GUI Applications with JavaFX and


Scene Builder

Slides in this presentation contain hyperlinks.


JAWS users should be able to get a list of links by
using INSERT+F7
Chapter Topics

15.1 Introduction
15.2 Scene Graphs
15.3 Using Scene Builder to Create JavaFX Applications
15.4 Writing the Application Code
15.5 RadioButtons and CheckBoxes
15.6 Displaying Images
15.1 Introduction

• JavaFX is a Java library for developing rich applications


that employ graphics.
• You can use it to create:
– GUI applications, as well as applications that display
2D and 3D graphics
– standalone graphics applications that run on your
local computer
– applications that run from a remote server
– applications that are embedded in a Web page
Various GUI Components
Some GUI Components
Event-Driven Programming

• Programs that operate in a GUI environment must be


event-driven.
• An event is an action that takes place within a program,
such as the clicking of a button.
• Part of writing a GUI application is creating event
listeners.
• An event listener is a method that automatically
executes when a specific event occurs.
15.2 Scene Graphs (1 of 4)

• In JavaFX, the components that are in a GUI are


organized as a scene graph.
• A scene graph is a tree-like, hierarchical data structure
that contains nodes.
15.2 Scene Graphs (2 of 4)
• A scene graph can have three types of nodes:
– Root Node:
▪ The scene graph can have only one root node.
▪ It is the parent of all the other nodes in the scene
graph.
▪ It is the first node in the structure.
– Branch Node:
▪ A branch node can have other nodes as children.
– Leaf Node:
▪ A leaf node cannot have children.
In a nutshell, the root node and branch nodes can have
children, but leaf nodes cannot.
15.2 Scene Graphs (3 of 4)

• In JavaFX, a node that can have children is a container.


• A container is a component that can hold other
components inside of it.
• The JavaFX library provides several different types of
containers.
15.2 Scene Graphs (4 of 4)
• The AnchorPane container is commonly used as a GUI’s root
node.
• A branch node is a container that is placed inside the root
node or inside another branch node.
– For example, you might have a Pane (one of the
simplest JavaFX containers) inside of an AnchorPane.
• A leaf node is a component that is not a container.
– For example, Button components and Label
components are leaf nodes.
Example GUI and Scene Graph
A More Complex GUI and Scene Graph

• The AnchorPane is the root node


– The TitledPane is a child of the AnchorPane
– it is contained inside the AnchorPane
▪ Another AnchorPane is a child of the TitledPane
▪ it is contained inside the TitledPane
▪ The Three RadioButtons are children of the innermost AnchorPane
– The Button is a child of the root node AnchorPane.
15.3 Using Scene Builder to Create JavaFX
Applications (1 of 2)
• Scene Builder is a free design tool from Oracle for visually creating GUIs.

• It works like this:


– Use Scene Builder to construct a GUI by dragging and dropping the
components that you need onto a blank window.
– Visually arrange the components on the window and set various
component properties to create the appearance that you want for the
GUI.
– Save the GUI to an FXML file.

• FXML is a markup language that describes the components in a JavaFX


scene graph.

• FXML uses tags to organize data, in a manner similar to the way that HTML
uses tags to format text in a Web browser.
15.3 Using Scene Builder to Create JavaFX
Applications (2 of 2)

• Visually creating a GUI with Scene Builder is only part of


the process.
• Once you save a GUI’s scene graph to an FXML file, the
next step is to write Java code that reads the FXML file
and displays the GUI on the screen and handles any
events that occur while the application is running.
Starting Scene Builder
• You can download Scene Builder from the following location:

www.oracle.com/technetwork/java/javafx/downloads/

• When you install Scene Builder in Windows, a shortcut is


automatically created on the desktop.
• You can launch Scene Builder either by double-clicking the shortcut,
or by going to All Programs > JavaFX Scene Builder and clicking
JavaFX Scene Builder x.x
– where x.x will be a version number such as 2.0
• If you installed Scene Builder on a Mac, go to the Applications folder
and double-click the shortcut for JavaFX Scene Builder x.x
– where x.x will be a version number such as 2.0
The Scene Builder Main Window
Using Scene Builder to Create the Kilometer
Converter GUI

• An AnchorPane, as the root node


• A Label to display the prompt Enter a distance in kilometers:
• A TextField in which the user will enter a distance
• A Label to display a message showing the distance converted to miles
• A Button that performs the conversion
15.4 Writing the Application Code

• Once you have saved an application’s GUI to an FXML


file, you can write the Java code that runs the application.
• A simple JavaFX application uses:
– a main application class
– a controller class
The Main Application Class

• Once you have created a GUI with Scene Builder, and


saved it to an FXML file, you need to write a Java class
that performs the following:
– Loads the FXML file
– Builds the scene graph in memory
– Displays the GUI
Example: KilometerCoverter.java
The Controller Class

• The controller class is responsible for handling events


that occur while the application is running.
• The controller class contains the following items:
– The necessary import statements
– Private variables to reference the components that
have a fx:id in the scene graph
– An optional initialize method that is automatically
called after the FXML file is loaded
– Event listener methods

Example: KilometerCoverterController.java
Using the Sample Controller Skeleton
• An alternative for manually typing the code for the controller class, Scene
Builder can provide a sample "skeleton" for the controller class.

• To see the sample controller skeleton, click the View menu, then click
Show Sample Controller Skeleton

• You can click the Copy button to copy the sample code to the clipboard,
and then paste it into an editing window in your IDE.

• The obvious benefit of using the sample skeleton controller is that a lot of
the code is written for you.

• The skeleton has all of the necessary import statements, and the class
already has private field declarations for all of the components that have an
fx:id.

• You just need to change the name of the class, and write the code for the
event listener methods.
Summary of Creating a JavaFX Application

• Use Scene Builder to design the GUI. Be sure to give an fx:id


to all of the components that you plan to access in your Java
code. Save the GUI as an FXML file.
• Write the code for the main application class, which loads the
FXML file and launches the application. Save and compile the
code in the same location as the FXML file.
• Write the code for the controller class, which contains the
event handler methods for the GUI. Save and compile the
code in the same location as the FXML file.
• In Scene Builder, register the controller class, then register an
event handler method for each component that needs to
respond to events. Save the FXML file again.
15.5 RadioButtons and CheckBoxes

• RadioButtons normally appear in groups of two or more


and allow the user to select one of several possible
options.
• CheckBoxes, which may appear alone or in groups, allow
the user to make yes/no or on/off selections.
RadioButtons

• RadioButtons are useful when you want the user to


select one choice from several possible options.
• A radio button may be selected or deselected.
• Each radio button has a small circle that appears filled-in
when the radio button is selected and appears empty
when the radio button is deselected.
Creating a RadioButton

• To create a RadioButton, you simply drag it from the


Library panel and drop it onto the Content panel.
• (The RadioButton component is found in the Controls
section of the Library panel.)
• RadioButtons have a Text property that determines the
text they display.
• RadioButtons normally are in a toggle group.
Adding RadioButtons to a Toggle Group
• Here are the steps for adding RadioButtons to a toggle group:
– Create the first RadioButton component in the Content panel.
– Open the Properties section of the Inspector Panel, and find the
Toggle Group property.
– Enter the name you wish to give the toggle group.
– Create the next RadioButton.
– For its Toggle Group property, you should be able to click the
down-arrow and select the toggle group that you created for the
first RadioButton.
– Repeat this for each subsequent RadioButton that you want in
the same toggle group.
Determining in Code Whether a
RadioButton is Selected
• In the controller class, you can use the RadioButton’s isSelected
method to determine whether the RadioButton is selected or not.
• The isSelected method returns a boolean value.
– If the RadioButton is selected, the method returns true.
Otherwise, it returns false.

Example: RadioButtonDemo.java, RadioButtonDemoController.java


Responding to RadioButton Events

• In many situations you want an action to take place at the


time the user clicks a RadioButton.
– you must write an event listener method in the
controller class for each RadioButton
– and then select the appropriate method as the event
listener in Scene Builder.
Example: RadioButtonEvent.java,
RadioButtonEventController.java
CheckBoxes

• A CheckBox is a small box with text appearing next to it.


• Like RadioButtons, CheckBoxes may be selected or
deselected at run time.
• When a CheckBox is selected, a small check mark
appears inside the box.
• Although CheckBoxes are often displayed in groups, they
are not usually grouped in a toggle group like
RadioButtons are.
Creating a CheckBox

• To create a CheckBox, you simply drag it from the Library


panel and drop it onto the Content panel.
• (The CheckBox component is found in the Controls
section of the Library panel.)
• CheckBoxes have a Text property that determines the
text they display.
Determining in Code Whether a CheckBox
is Selected
• In the controller class, you can use the CheckBox’s isSelected
method to determine whether the CheckBox is selected or not.
• The isSelected method returns a boolean value.
– If the CheckBox is selected, the method returns true. Otherwise,
it returns false.

Example: CheckBoxDemo.java, CheckBoxDemoController.java


Responding to CheckBox Events
• Sometimes you want an action to take place at the time the
user clicks a CheckBox.
– you must write an event listener method in the controller
class for the CheckBox
– and then select the method as the event listener in Scene
Builder.
Example: CheckBoxEvent.java, CheckBoxEventController.java
15.6 Displaying Images

• You can use the ImageView component to display


images in an application’s GUI.
• You simply drag the component from the Library panel
(you will find it in the Controls section) and drop it onto
the Content Panel
• Once you have created a ImageView component, you
use its Image property to specify the image that it will
display.
Displaying an Image with Code (1 of 3)

• Sometimes you might need to write code that will change


the image being displayed in an ImageView component,
as the application is running.
• In your controller class, you can call the ImageView
component's setImage method to do this.
Displaying an Image with Code (2 of 3)
• First, you must create an instance of the Image class, which
can read the contents of an image file.
• The Image class is in the javafx.scene.image package.
• The Image class constructor accepts a String argument that
is the name of an image file.
• Here is an example:

• Here is an example that uses a path.


Displaying an Image with Code (3 of 3)
• Once you have created an Image object, you pass a
reference to that object to the ImageView component's
setImage method.
• The following is an example:
– Assume that myImageView references an
ImageView component, and myImage references an
Image object.

Example: ImageViewDemo.java,
ImageViewDemoController.java
Chapter 12

Introduction, GUI Applications using Swing


(optional)
12.2 Creating Windows (1 of 7)
• Often, applications need one or more windows with various
components.
• A window is a container, which is simply a component that
holds other components.
• A container that can be displayed as a window is a frame.
• In a Swing application, you create a frame from the JFrame
class.
12.2 Creating Windows (2 of 7)

• A frame is a basic window that has:


– a border around it,
– a title bar, and
– a set of buttons for:
▪ minimizing,
▪ maximizing, and
▪ closing the window.
• These standard features are sometimes referred to as
window decorations.
12.2 Creating Windows (3 of 7)

• See example: ShowWindow.java


12.2 Creating Windows (4 of 7)
• The following import statement is needed to use the swing
components:

• In the main method, two constants are declared:

• We use these constants later in the program to set the size of the
window.
• The window’s size is measured in pixels.
• A pixel (picture element) is one of the small dots that make up a
screen display.
12.2 Creating Windows (5 of 7)
• An instance of the JFrame class needs to be created:

• This statement:
– creates a JFrame object in memory and
– assigns its address to the window variable.
• The string that is passed to the setTitle method will appear in
the window’s title bar when it is displayed.

• A JFrame is initially invisible.


12.2 Creating Windows (6 of 7)
• To set the size of the window:

• To specify the action to take place when the user clicks on the
close button.

• The setDefaultCloseOperation method takes an int


argument which specifies the action.
– - causes the window to be hidden
from view, but the application does not end.
– The default action is
12.2 Creating Windows (7 of 7)

• The following code displays the window:

• The setVisible method takes a boolean argument.


– true - display the window.
– false - hide the window.
Extending JFrame
• We usually use inheritance to create a new class that extends the
JFrame class.

• When a new class extends an existing class, it inherits many of the


existing class’s members just as if they were part of the new class.
• These members act just as if they were written into the new class
declaration.
• New fields and methods can be declared in the new class
declaration.
• This allows specialized methods and fields to be added to your
window.
• Examples: SimpleWindow.java, SimpleWindowDemo.java
12.3 Equipping GUI Classes with a Main
Method

• Java applications always starts execution with a method


named main.
• The previous example used two separate files:
– SimpleWindow.java — the class that defines the GUI
window
– SimpleWindowDemo.java – containins the main
method that creates an instance of the SimpleWindow
class.
• Applications can also be written with the main method directly
written into the GUI class.
• See example: EmbeddedMain.java
Adding Components (1 of 5)

• Swing provides numerous components that can be added


to a window.
• Three fundamental components are:
JLabel : An area that can display text.
JTextField : An area in which the user may type a
single line of input from the keyboard.
JButton : A button that can cause an action to occur
when it is clicked.
Sketch of Kilometer Converter Graphical
User Interface
Adding Components (2 of 5)

• This code declares and instantiates three Swing components.


Adding Components (3 of 5)
• A content pane is a container that is part of every JFrame
object.
• Every component added to a JFrame must be added to its
content pane. You do this with the JFrame class’s add
method.
• The content pane is not visible and it does not have a border.
• A panel is also a container that can hold GUI components
Adding Components (4 of 5)

• Panels cannot be displayed by themselves.


• Panels are commonly used to hold and organize
collections of related components.
• Create panels with the JPanel class.
Adding Components (5 of 5)

• Components are typically placed on a panel and then the


panel is added to the Jframe’s content pane.

• Examples: KiloConverter.java
Handling Action Events (1 of 4)
• An event is an action that takes place within a program, such
as the clicking of a button.
• When an event takes place, the component that is responsible
for the event creates an event object in memory.
• The event object contains information about the event.
• The component that generated the event object is know as the
event source.
• It is possible that the source component is connected to one or
more event listeners.
Handling Action Events (2 of 4)

• An event listener is an object that responds to events.


• The source component fires an event which is passed to
a method in the event listener.
• Event listener classes are specific to each application.
• Event listener classes are commonly written as private
inner classes in an application.
Writing Event Listener Classes as Private
Inner Classes

A class that is defined inside of another class is known as an


inner class
Event Listeners Must Implement an
Interface

• All event listener classes must implement an interface.


• An interface is something like a class containing one or
more method headers.
• When you write a class that implements an interface, you
are agreeing that the class will have all of the methods
that are specified in the interface.
Handling Action Events (3 of 4)
• JButton components generate action events, which require
an action listener class.
• Action listener classes must meet the following requirements:
– It must implement the ActionListener interface.
– It must have a method named actionPerformed.
• The actionPerformed method takes an argument of the
ActionEvent type.
Handling Action Events (4 of 4)

When the button is pressed …


The JButton component generates an event object and passes
it to the action listener object’s actionPerformed method.
Example: KiloConverter.java
Registering a Listener

• The process of connecting an event listener object to a


component is called registering the event listener.
• JButton components have a method named
addActionListener.

• When the user clicks on the source button, the action


listener object’s actionPerformed method will be
executed.

You might also like