This document provides an overview of GUI design using JavaFX. It begins with an introduction and outline, then discusses application development and GUI programming in Java using AWT, Swing, and JavaFX. It covers topics like components, containers, events, listeners, and layouts. The document also compares AWT, Swing and JavaFX, and provides examples of creating GUI components and handling events in JavaFX.
The presentation given at MSBTE sponsored content updating program on 'Advanced Java Programming' for Diploma Engineering teachers of Maharashtra. Venue: Guru Gobind Singh Polytechnic, Nashik
Date: 22/12/2010
Session: Java Network Programming
Source code: https://github.com/MohdShamweel/TheBr
College Project developed in JavaFx.
avaFX is a software platform for creating and delivering desktop applications, as well as rich Internet applications (RIAs) that can run across a wide variety of devices. JavaFX is intended to replace Swing as the standard GUI library for Java SE, but both will be included for the foreseeable future.[3] JavaFX has support for desktop computers and web browsers on Microsoft Windows, Linux, and macOS. JavaFX is no longer bundled with the latest Java, nor will be supported by Oracle, while it still is supported for the current long-term version Java SE 8 through March 2022.
WebView, the embedded browser component supports the following HTML5 features:
Canvas,
Media playback,
Form controls (except for <input type="color"> ),
Editable content,
History maintenance,
Support for the <meter> and <progress> tags,
Support for the <details> and <summary> tags,
DOM,
MathML,
SVG,
Support for domain names written in national languages.
JavaFX Applications
Written as a Java API, JavaFX application code can reference APIs from any Java library. For example, JavaFX applications can use Java API libraries to access native system capabilities and connect to server-based middleware applications.
The look and feel of JavaFX applications can be customized. Cascading Style Sheets (CSS) separate appearance and style from implementation so that developers can concentrate on coding. Graphic designers can easily customize the appearance and style of the application through the CSS. If you have a web design background, or if you would like to separate the user interface (UI) and the back-end logic, then you can develop the presentation aspects of the UI in the FXML scripting language and use Java code for the application logic. If you prefer to design UIs without writing code, then use JavaFX Scene Builder. As you design the UI, Scene Builder creates FXML markup that can be ported to an Integrated Development Environment (IDE) so that developers can add the business logic.
The presentation given at MSBTE sponsored content updating program on 'Advanced Java Programming' for Diploma Engineering teachers of Maharashtra. Venue: Guru Gobind Singh Polytechnic, Nashik
Date: 22/12/2010
Session: Java Network Programming
Source code: https://github.com/MohdShamweel/TheBr
College Project developed in JavaFx.
avaFX is a software platform for creating and delivering desktop applications, as well as rich Internet applications (RIAs) that can run across a wide variety of devices. JavaFX is intended to replace Swing as the standard GUI library for Java SE, but both will be included for the foreseeable future.[3] JavaFX has support for desktop computers and web browsers on Microsoft Windows, Linux, and macOS. JavaFX is no longer bundled with the latest Java, nor will be supported by Oracle, while it still is supported for the current long-term version Java SE 8 through March 2022.
WebView, the embedded browser component supports the following HTML5 features:
Canvas,
Media playback,
Form controls (except for <input type="color"> ),
Editable content,
History maintenance,
Support for the <meter> and <progress> tags,
Support for the <details> and <summary> tags,
DOM,
MathML,
SVG,
Support for domain names written in national languages.
JavaFX Applications
Written as a Java API, JavaFX application code can reference APIs from any Java library. For example, JavaFX applications can use Java API libraries to access native system capabilities and connect to server-based middleware applications.
The look and feel of JavaFX applications can be customized. Cascading Style Sheets (CSS) separate appearance and style from implementation so that developers can concentrate on coding. Graphic designers can easily customize the appearance and style of the application through the CSS. If you have a web design background, or if you would like to separate the user interface (UI) and the back-end logic, then you can develop the presentation aspects of the UI in the FXML scripting language and use Java code for the application logic. If you prefer to design UIs without writing code, then use JavaFX Scene Builder. As you design the UI, Scene Builder creates FXML markup that can be ported to an Integrated Development Environment (IDE) so that developers can add the business logic.
Applications use in Java GUIThe Java GUI consists of a separate, .pdfakshay1213
Applications use in Java GUI:
The Java GUI consists of a separate, automous task execution thread called the \"event loop\".
Every action that affects the GUI, e.g. calls to repaint the screen or to manipulate the properties
of a GUI component, or is a result of something happening to the GUI, e.g. the user clicks the
mouse or hits a key, is encapsulated in the form of an \"event\" that is placed into a queue for the
event loop to process. The result of processing an event may be a manipulation of the bits of
color on the screen or it may result in calls to methods in the developer\'s code.
1.A Java GUI application uses the standard Java components GUI component set, Swing, and is
deployed to the desktop.
2.The Swing GUI Builder in NetBeans IDE simplifies the GUI development process and enables
you to visually create Java GUI applications using pre-installed Swing and AWT components.
3.JavaFX is a rich set of graphics and media packages that enables developers to design, create,
test, debug, and deploy rich client applications (RIAs) that behave consistently across multiple
platforms.
Similariti Between JAVA and JAVA GUI:
I think in many cases the overhead incurred to run a JVM is acceptable because of the
functionality the code base
provides.So winding back a bit, the reason that functionality can exist with Java has much to do
with the language/environment which frees programmers from a lot of resource management and
allows them to focus
more on plugging together components. Time to market and all that jazz.Like a lot of interpreted
languages, Java\'s development cycle ispretty excellent I think. A programmer can get a fairly
complicatedapplication off the ground quickly due to a number of things broughtabout both by
the interp-language development paradigm that allows for
immediate detection of errors and compile-and-test-as-you-code sessions.I think those are the
kinds of things which has made Java popular.
Some Java applications that you can install and play with on your own desktop machine:
1.Eclipse
2.NetBeans
3.jEdit
4.OpenOffice
Java is used in
JAVA GUI:
The Java GUI system however is a legacy issue where the system underwent a large-scale
upgrade , so some of the classes involved are spread over the (relatively) older java.awt packages
and the newer javax.swing packages. In general, if the class name starts with \"J\", then it is in
the Swing package. Since some functionality appears to be duplicated in the Swing packages,
such as frames and buttons, always use the Swing component over the older AWT components
when there is a choice.
Commonly Used Methods in GUI Components:
void setPreferredSize(int width, int height) :sets the size of a component to be used when the
layout manager is able to use that size, e.g. there is enough room. Some layout managers always
ignore the size setting of a component because the size is under other constraints..
String getText(), void setText(String s) :accessor methods for the text of labels, button.
java...... it connet
Learn the workings of using intelligent machines for your processes using content-ready Artificial Intelligence PowerPoint Presentation Slides. Processes like learning, reasoning, self-correction, etc. are executed by artificial intelligent machines. Incorporate ready-made artificial intelligence PPT presentation templates and maximize the chance of achieving the organizational goals. This deck comprises of templates such as artificial intelligence objectives, artificial intelligence components, artificial intelligence statistics, artificial intelligence & investment by sector, artificial intelligence in various sectors, core areas of artificial intelligence, artificial intelligence value chain elements, artificial intelligence development phases, artificial intelligence approaches, machine learning (pattern based), machine learning description, machine learning process, machine learning use cases, and more. These templates are customizable. Edit color, text, icon and font size as per your need. Grab easy-to-understand artificial intelligence PowerPoint presentation slideshow and perform tasks associated with intelligent beings. Find solutions to the business problems without human intervention. PrFeatures of these PowerPoint presentation slides:
Presenting artificial intelligence presentation slides. This deck comprises of total of 50 slides. Each slide includes professional visuals with an appropriate content. These templates have been designed keeping the customers requirement in mind. This complete presentation covers all the design elements such as layout, diagrams, icons, and more. This deck has been crafted after an extensive research. You can easily customize each template. Edit the color, text, icon, and font size as per your requirement. Easy to download. Compatible with all screen types and monitors. Supports Google Slides. Premium Customer Support available.
Features of these PowerPoint presentation slides:
Presenting artificial intelligence presentation slides. This deck comprises of total of 50 slides. Each slide includes professional visuals with an appropriate content. These templates have been designed keeping the customers requirement in mind. This complete presentation covers all the design elements such as layout, diagrams, icons, and more. This deck has been crafted after an extensive research. You can easily customize each template. Edit the color, text, icon, and font size as per your requirement. Easy to download. Compatible with all screen types and monitors. Supports Google Slides. Premium Customer Support available.
Features of these PowerPoint presentation slides:
Presenting artificial intelligence presentation slides. This deck comprises of total of 50 slides. Each slide includes professional visuals with an appropriate content. These templates have been designed keeping the customers requirement in mind. This complete presentation covers all th
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSEDuvanRamosGarzon1
AIRCRAFT GENERAL
The Single Aisle is the most advanced family aircraft in service today, with fly-by-wire flight controls.
The A318, A319, A320 and A321 are twin-engine subsonic medium range aircraft.
The family offers a choice of engines
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Immunizing Image Classifiers Against Localized Adversary Attacksgerogepatton
This paper addresses the vulnerability of deep learning models, particularly convolutional neural networks
(CNN)s, to adversarial attacks and presents a proactive training technique designed to counter them. We
introduce a novel volumization algorithm, which transforms 2D images into 3D volumetric representations.
When combined with 3D convolution and deep curriculum learning optimization (CLO), itsignificantly improves
the immunity of models against localized universal attacks by up to 40%. We evaluate our proposed approach
using contemporary CNN architectures and the modified Canadian Institute for Advanced Research (CIFAR-10
and CIFAR-100) and ImageNet Large Scale Visual Recognition Challenge (ILSVRC12) datasets, showcasing
accuracy improvements over previous techniques. The results indicate that the combination of the volumetric
input and curriculum learning holds significant promise for mitigating adversarial attacks without necessitating
adversary training.
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfKamal Acharya
The College Bus Management system is completely developed by Visual Basic .NET Version. The application is connect with most secured database language MS SQL Server. The application is develop by using best combination of front-end and back-end languages. The application is totally design like flat user interface. This flat user interface is more attractive user interface in 2017. The application is gives more important to the system functionality. The application is to manage the student’s details, driver’s details, bus details, bus route details, bus fees details and more. The application has only one unit for admin. The admin can manage the entire application. The admin can login into the application by using username and password of the admin. The application is develop for big and small colleges. It is more user friendly for non-computer person. Even they can easily learn how to manage the application within hours. The application is more secure by the admin. The system will give an effective output for the VB.Net and SQL Server given as input to the system. The compiled java program given as input to the system, after scanning the program will generate different reports. The application generates the report for users. The admin can view and download the report of the data. The application deliver the excel format reports. Because, excel formatted reports is very easy to understand the income and expense of the college bus. This application is mainly develop for windows operating system users. In 2017, 73% of people enterprises are using windows operating system. So the application will easily install for all the windows operating system users. The application-developed size is very low. The application consumes very low space in disk. Therefore, the user can allocate very minimum local disk space for this application.
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
Courier management system project report.pdfKamal Acharya
It is now-a-days very important for the people to send or receive articles like imported furniture, electronic items, gifts, business goods and the like. People depend vastly on different transport systems which mostly use the manual way of receiving and delivering the articles. There is no way to track the articles till they are received and there is no way to let the customer know what happened in transit, once he booked some articles. In such a situation, we need a system which completely computerizes the cargo activities including time to time tracking of the articles sent. This need is fulfilled by Courier Management System software which is online software for the cargo management people that enables them to receive the goods from a source and send them to a required destination and track their status from time to time.
Cosmetic shop management system project report.pdfKamal Acharya
Buying new cosmetic products is difficult. It can even be scary for those who have sensitive skin and are prone to skin trouble. The information needed to alleviate this problem is on the back of each product, but it's thought to interpret those ingredient lists unless you have a background in chemistry.
Instead of buying and hoping for the best, we can use data science to help us predict which products may be good fits for us. It includes various function programs to do the above mentioned tasks.
Data file handling has been effectively used in the program.
The automated cosmetic shop management system should deal with the automation of general workflow and administration process of the shop. The main processes of the system focus on customer's request where the system is able to search the most appropriate products and deliver it to the customers. It should help the employees to quickly identify the list of cosmetic product that have reached the minimum quantity and also keep a track of expired date for each cosmetic product. It should help the employees to find the rack number in which the product is placed.It is also Faster and more efficient way.
Automobile Management System Project Report.pdfKamal Acharya
The proposed project is developed to manage the automobile in the automobile dealer company. The main module in this project is login, automobile management, customer management, sales, complaints and reports. The first module is the login. The automobile showroom owner should login to the project for usage. The username and password are verified and if it is correct, next form opens. If the username and password are not correct, it shows the error message.
When a customer search for a automobile, if the automobile is available, they will be taken to a page that shows the details of the automobile including automobile name, automobile ID, quantity, price etc. “Automobile Management System” is useful for maintaining automobiles, customers effectively and hence helps for establishing good relation between customer and automobile organization. It contains various customized modules for effectively maintaining automobiles and stock information accurately and safely.
When the automobile is sold to the customer, stock will be reduced automatically. When a new purchase is made, stock will be increased automatically. While selecting automobiles for sale, the proposed software will automatically check for total number of available stock of that particular item, if the total stock of that particular item is less than 5, software will notify the user to purchase the particular item.
Also when the user tries to sale items which are not in stock, the system will prompt the user that the stock is not enough. Customers of this system can search for a automobile; can purchase a automobile easily by selecting fast. On the other hand the stock of automobiles can be maintained perfectly by the automobile shop manager overcoming the drawbacks of existing system.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
4. GUI BASED PROGRAMMING IN JAVA
GUI Is An Interface That Interacts With User And Source Code.
It Makes The Software User Friendly. So, Users Interact With
The Interface And That Interface Interacts With Source Code.
GUI BASED PROGRAMMING IN JAVA
Java Abstract Window Toolkit (AWT)
Java Swing
JavaFX
5. AWT: ABSTRACT WINDOWING TOOLKIT
It’s an API used to develop GUI for windows-based applications in the
java programming language.
AWT is platform dependent
AWT components are heavyweight
Java’s Abstract Window Toolkit provides classes and other tools for
building programs that have a graphical user interface.
Syntax :
import java.awt.*;
5
6. SWING:
It’s an API used to develop GUI for desktop-based
applications in the java programming language.
SWING components are lightweight
Are platform independent
It follows MVC architecture
Extends AWT
Syntax :
import javax.swing.*
6
7. JAVAFX
JavaFX a versatile cross OS and cross device application toolkit
JavaFX comes with a rich set of GUI controls, and open source
toolkits
JavaFX comes with a large set of built-in GUI components, like
buttons, text fields, tables, trees, menus, charts and much more.
JavaFX can be styled via CSS and / or programmatically.
JavaFX comes with a built-in chart library and supports 2D and 3D
graphics.
7
8. MVC ARCHITECTURE
Model: Handles data and business logic.
View: Presents the data to the user whenever asked for.
Controller: It controls the data flow into a model object
and updates the view whenever data changes.
9
9. AWT VS SWING VS JAVAFX
CHARACTERISTIC AWT SWING JavaFX
DEPENDENCY
Platform Depen
dent
Platform
Independent
Platform
Independent
WEIGHT OF
COMPONENT
Heavyweight Lightweight Lightweight
CURRENTLY IN
USE
Discarded
Use It In A Few
Places.
Currently In Use
PLUGGABLE
Does Not Support
A Pluggable Look
And Feel
Support Pluggable
Look And Feel.
Components Look
The Same On All
Systems
Support Pluggable
Look And Feel.
Components Look
The Same On All
Systems.
10
10. AWT VS SWING VS JAVAFX
CHARACTERISTIC AWT SWING JavaFX
MVC
Does Not Follow
MVC
Follow MVC Follow MVC.
NO. OF
COMPONENTS
Less More Than AWT
More Than AWT
But Less Than
SWING.
PACKAGE Java.Awt.Package Javax.Swing Javafx.Util
RELEASED 1995 1997 2008
11
12. AWT CLASS HIERARCHY (CONT..)
13
Container
The Container is a component in AWT that can contain another
components like buttons, textfields, labels etc. The classes that
extends Container class are known as container such as Frame,
Dialog and Panel.
Window
The window is the container that have no borders and menu bars.
You must use frame, dialog or another window for creating a
window.
Panel
The Panel is the container that doesn't contain title bar and menu
bars. It can have other components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu
bars. It can have other components like button, textfield etc.
14. CREATING A GRAPHICAL USER INTERFACE
GUI programming in Java is based on three
concepts:
Components. A component is an object that the user can
see on the screen and in most cases interact with.
Containers. A container is a component that can hold
other components.
Events. An event is an action triggered by the user, such
as a key press or mouse click.
Designing a graphical user interface involves
creating components, putting them into containers,
and arranging for the program to respond to events.
15
15. CREATING A GRAPHICAL USER INTERFACE
Components are objects, so they’re created by
invoking a constructor.
A button would be created by using a constructor
belonging to the Button class.
The most commonly used constructor has one
argument (the button’s label):
Button b = new Button("Testing");
16
16. CREATING A GRAPHICAL USER INTERFACE
For a component to be visible, it must be added to
a container (typically a frame) by the add method in
swing.
To detect when an event occurs, a special “listener”
object can be attached to a component.
When the user performs an action that involves the
component, a method belonging to the listener
object will be called automatically.
17
17. GUI COMPONENT API
Java: GUI component = class
Properties
Methods
Events
Button
18. USING A GUI COMPONENT
1. Create it
2. Configure it
3. Add children (if container)
4. Add to parent (if not JFrame)
5. Listen to it
order
important
19. USING A GUI COMPONENT
1. Create it
Instantiate object:
Button b = new Button();
2. Configure it
Methods: b.setText(“press me”);
3. Add it
panel.add(b);
4. Listen to it
Events: Listeners
Button
24. RHS
–
SOC
GUI CONSTRUCTION
In general, we have two options when constructing
a GUI
Build it ”by hand” using Swing API
Use the IDE like netbeans, eclipse, scene builder,
JavaFX
Using the GUI Builder is usually much easier than
hand-coding the GUI
25. INTRODUCTION TO IDE
An Integrated Development
Environment is a computer software
to help computer programmers develop
software.
The Leaders:
- NetBeans
- Microsoft Visual Studio
- Eclipse
26. INTRODUCTION TO IDE- CONT.
What does an IDE consist of:
- Source code Editor.
- Compiler and/or interpreter.
- Build- automation tools.
Optional Tools:
- Debugger.
- Various tools to simplify the construction of a
GUI.
27. JavaFX has 3 parts
A GUI builder called SceneBuilder allows drag-
and-drop manipulation of widgets.
A configuration language called FXML that
records the widgets in the GUI, their visible
attributes and their relationship to each other.
A Controller class that must be completed by the
programmer to bring the GUI to life.
A JavaFX application has some additional parts
A set of classes to describe the model, which is what
the GUI allows the user to interact with.
A set of cascading style sheets (CSS files) to further
specify “look-and-feel”.
JAVAFX PARTS
28. JAVAFX SCENE BUILDER
JavaFX Scene Builder is a standalone JavaFX GUI
visual layout tool that can also be used with various
IDEs including eclipse, NetBeans and IntelliJ.
JavaFX Scene Builder enables you to create GUIs
by dragging and dropping GUI components from
Scene Builder’s library onto a design area, then
modifying and styling the GUI—all without writing
any code.
JavaFX Scene Builder generates FXML (FX
Markup Language)—an XML vocabulary for
defining and arranging JavaFX GUI controls without
writing any Java code.
29. JAVAFX SCENE BUILDER (CONT.)
The FXML code is separate from the program logic
that’s defined in Java source code—this separation
of the interface (the GUI) from the implementation
(the Java code) makes it easier to debug, modify
and maintain JavaFX GUI apps.
Placing GUI components in a window can be
tedious. Being able to do it dynamically using a
configuration file makes the job much easier.
No additional compilation is needed unless actions
need to be programmed in the Controller.java class.
32. JAVAFX APP WINDOW STRUCTURE (CONT.)
The Stage is the window in which a JavaFX app’s
GUI is displayed
It’s an instance of class Stage (package
javafx.stage).
The Stage contains one active Scene that defines
the GUI as a scene graph—a tree data structure of
an app’s visual elements, such as GUI controls,
shapes, images, video, text and.
The scene is an instance of class Scene (package
javafx.scene).
Controls are GUI components, such as
Labels that display text,
TextFields that enable a program to receive user
input,
Buttons that users click to initiate actions, and more.
33. An application Window in JavaFX is known as a
Stage.
package javafx.stage
A Stage contains an active Scene which is set to a
Layout container.
package javafx.scene
The Scene may have other Layout containers for
organizing Controllers in a Tree organization.
Nodes with children are layout containers.
Nodes without children are widgets.
JAVAFX APPLICATION LAYOUT
34. JAVAFX APP WINDOW STRUCTURE (CONT.)
Each visual element in the scene graph is a node—
an instance of a subclass of Node (package
javafx.scene), which defines common attributes
and behaviors for all nodes
With the exception of the first node in the scene
graph—the root node—each node in the scene
graph has one parent.
Nodes can have transforms (e.g., moving, rotating
and scaling), opacity (whether a node is
transparent, partially transparent or opaque),
effects (e.g., drop shadows, blurs, reflection and
lighting) and more.
35. JAVAFX CONTROLS
Nodes with children are typically layout containers that
arrange their child nodes in the scene.
Layout containers contain controls that accept inputs or other
layout containers.
When the user interacts with a control, the control
generates an event.
Programs can respond to these events—known as event
handling—to specify what should happen when each
user interaction occurs.
An event handler is a method that responds to a user
interaction. An FXML GUI’s event handlers are defined in
a so-called controller class.
36. import javafx.application.Application; import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane; import
javafx.scene.control.Button;
public class ButtonInPane extends Application {
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Create a scene and place a button in the scene StackPane pane =
new StackPane(); pane.getChildren().add(new Button("OK"));
Scene scene = new Scene(pane, 200, 50);
primaryStage.setTitle("Button in a pane"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public static void main(String[] args) { launch(args);
}
}
37
39. (c) Paul Fodor and Pearson Inc.
SHAPES
JAVAFX PROVIDES MANY SHAPE CLASSES
FOR DRAWING TEXTS, LINES, CIRCLES,
RECTANGLES, ELLIPSES, ARCS, POLYGONS,
AND POLYLINES.
35
4
8
41. FXML
⚫FXML is a declarative XML-based language
created by Oracle Corporation for defining the
user interface of a JavaFX 2.0 application.
⚫It can be edited and created using the JavaFX
Scene Builder 2 (downloaded separately from
J2SE)
⚫Create a new JavaFX project in Netbeans and
you will get 3 files: an FXML file with the UI
design, a main application .java file that loads
the FXML and a controller for the event
handlers for the UI Nodes.
59
5
9
45. (c) Paul Fodor and Pearson Inc.
25
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene; import
javafx.scene.layout.Pane; import
javafx.scene.layout.HBox; import
javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.geometry.Insets;
public class ShowImage extends Application {
@Override
public void start(Stage primaryStage) {
// Create a pane to hold the image views Pane
pane = new HBox(10); pane.setPadding(new
Insets(5, 5, 5, 5)); Image image = new
Image("paul.jpg");
pane.getChildren().add(new ImageView(image));
ImageView imageView2 = new ImageView(image);
imageView2.setFitHeight(100);
imageView2.setFitWidth(100);
imageView2.setRotate(90);
pane.getChildren().add(imageView2);
Scene scene = new Scene(pane);
primaryStage.setTitle("ShowImage");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
6
3
46. JAVA’S EVENT HANDLING
⚫An eventsourceis aGUI control
⚫JavaFX:Button, ChoiceBox, ListView, etc.
http://docs.oracle.com/javase/8/javafx/user-interface-tutorial/ui_controls.htm
⚫different types of sources:
⚫can detect different types of events
⚫can register different types of listeners(handlers)
64
6
4
47. JAVA’S EVENT HANDLING
⚫When the user interacts with a control
(source):
⚫an event object is constructed
⚫the event object is sent to all registered
listener objects
⚫the listener object (handler) responds as
you defined it to
65
6
5
48. EVENT LISTENERS (EVENT HANDLER)
⚫Defined byyou, the application
programmer
⚫you customize the response
⚫How?
⚫Inheritance &Polymorphism
⚫Y
ou define your own listener class
⚫implement the appropriate interface
⚫define responses in all necessarymethods
66
6
6
49. EVENT OBJECTS
⚫Contain information about the event
⚫Like what?
⚫location of mouse click
⚫event source that was interacted with
⚫etc.
⚫Listeners use them to properly respond
⚫different methods inside a listener object
can react differently to different types of
interactions
67
6
7
50. HANDLING GUI EVENTS
⚫Source object: button.
⚫An event is generated by external user actions such as mouse
movements, mouse clicks, or keystrokes.
⚫An event can be defined as a type of signal to the program
that something has happened.
⚫Listener object contains a method for processing the
event.
68
52. EVENT INFORMATION
⚫An event object contains whatever
properties are pertinent to the event:
⚫the source object of the event using the
getSource() instance method in the
EventObject class.
⚫The subclasses of EventObject deal with
special types of events, such as button
actions, window events, component events,
mouse movements, and keystrokes.
70
55. LABELED CLASS
⚫A label is a display area for a short text, a node, or both
⚫It is often used to label other controls (usually text fields)
⚫Labels and buttons share many common properties: these
common
properties are defined in the Labeled class
75
7
5
57. import javafx.application.Application; import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.ContentDisplay; import
javafx.scene.control.Label;
import javafx.scene.image.Image; import javafx.scene.image.ImageView; import
javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import
javafx.scene.paint.Color; import javafx.scene.shape.Circle; import
javafx.scene.shape.Rectangle; import javafx.scene.shape.Ellipse;
public class LabelWithGraphic extends Application {
@Override
public void start(Stage primaryStage) {
ImageView us = new ImageView(new Image("us.jpg")); Label lb1 = new
Label("USn50 States", us);
lb1.setStyle("-fx-border-color: green; -fx-border-width: 2");
lb1.setContentDisplay(ContentDisplay.BOTTOM);
lb1.setTextFill(Color.RED);
Label lb2 = new Label("Circle", new Circle(50, 50, 25));
lb2.setContentDisplay(ContentDisplay.TOP);
lb2.setTextFill(Color.ORANGE);
Label lb3 = new Label("Retangle", new Rectangle(10, 10, 50, 25));
lb3.setContentDisplay(ContentDisplay.RIGHT);
Label lb4 = new Label("Ellipse", new Ellipse(50, 50, 50, 25));
lb4.setContentDisplay(ContentDisplay.LEFT);
77
7
7
58. Ellipse ellipse = new Ellipse(50, 50, 50, 25);
ellipse.setStroke(Color.GREEN);
ellipse.setFill(Color.WHITE);
StackPane stackPane = new StackPane();
stackPane.getChildren().addAll(ellipse, new Label("JavaFX"));
Label lb5 = new Label("A pane inside a label", stackPane);
lb5.setContentDisplay(ContentDisplay.BOTTOM);
HBox pane = new HBox(20); pane.getChildren().addAll(lb1,
lb2, lb3, lb4, lb5);
Scene scene = new Scene(pane, 700, 150);
primaryStage.setTitle("LabelWithGraphic");
primaryStage.setScene(scene); primaryStage.show();
}
public static void main(String[] args) { launch(args);
}
}
78
7
8
59. (c) Paul Fodor and Pearson Inc.
BUTTONBASE AND BUTTON
⚫A button is a control that triggers an action event when
clicked.
⚫JavaFX provides regular buttons, toggle buttons, check box
buttons, and radio buttons.
⚫The common features of these buttons are defined in
ButtonBase and Labeled classes.
79
7
9
60. import javafx.application.Application; import javafx.stage.Stage;
import javafx.geometry.Pos; import javafx.scene.Scene;
import javafx.scene.control.Button; import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane; import javafx.scene.text.Text;
public class ButtonDemo extends Application { @Override
public void start(Stage primaryStage) {
Scene scene = new Scene(getPane(), 450, 200);
primaryStage.setTitle("ButtonDemo"); primaryStage.setScene(scene);
primaryStage.show();
}
protected Text text = new Text(50, 50, "JavaFX Programming");
protected BorderPane getPane() {
HBox paneForButtons = new HBox(20);
Button btLeft = new Button("Left", new ImageView("image/left.gif")); Button
btRight = new Button("Right", new ImageView("image/right.gif"));
paneForButtons.getChildren().addAll(btLeft, btRight);
paneForButtons.setAlignment(Pos.CENTER);
paneForButtons.setStyle("-fx-border-color: green"); BorderPane pane = new
BorderPane(); pane.setBottom(paneForButtons);
80
8
0
62. (c) Paul Fodor and Pearson Inc.
CHECKBOX
⚫A CheckBox is used for the user to make a selection (square
box).
⚫CheckBox inherits all the properties from ButtonBase and
Labeled: onAction, text, graphic, alignment,
graphicTextGap, textFill, contentDisplay.
82
8
2
63. import javafx.event.ActionEvent; import
javafx.event.EventHandler; import javafx.geometry.Insets;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.BorderPane; import
javafx.scene.layout.VBox; import javafx.scene.text.Font;
import javafx.scene.text.FontPosture; import
javafx.scene.text.FontWeight;
public class CheckBoxDemo extends ButtonDemo {
@Override // Override the getPane() method in the super class
protected BorderPane getPane() {
BorderPane pane = super.getPane();
Font fontBoldItalic = Font.font("Times New Roman",
FontWeight.BOLD, FontPosture.ITALIC, 20);
Font fontBold = Font.font("Times New Roman", FontWeight.BOLD,
FontPosture.REGULAR, 20);
Font fontItalic = Font.font("Times New Roman",
FontWeight.NORMAL, FontPosture.ITALIC, 20);
Font fontNormal = Font.font("Times New Roman",
FontWeight.NORMAL, FontPosture.REGULAR, 20);
text.setFont(fontNormal);
VBox paneForCheckBoxes = new VBox(20);
paneForCheckBoxes.setPadding(new Insets(5, 5, 5, 5));
paneForCheckBoxes.setStyle("-fx-border-color: green");
83
8
3
64. CheckBox chkBold = new CheckBox("Bold"); CheckBox chkItalic =
new CheckBox("Italic");
paneForCheckBoxes.getChildren().addAll(chkBold, chkItalic);
pane.setRight(paneForCheckBoxes);
EventHandler<ActionEvent> handler = e -> {
if (chkBold.isSelected() && chkItalic.isSelected()) {
text.setFont(fontBoldItalic); // Both check boxes checked
} else if (chkBold.isSelected()) { text.setFont(fontBold); //
The Bold check box checked
} else if (chkItalic.isSelected()) { text.setFont(fontItalic);
// The Italic check box checked
} else {
text.setFont(fontNormal); // Both check boxes unchecked
}
};
chkBold.setOnAction(handler); chkItalic.setOnAction(handler);
return pane; // Return a new pane
}
// the start method is inherited from the superclass ButtonDemo
public static void main(String[] args) {
launch(args);
}
}
84
8
4
65. RADIOBUTTON
⚫Radio buttons allow to choose a single item from a group of
choices.
⚫Radio buttons display a circle that is either filled (if selected) or
blank (if not selected).
85
8
5
66. (c) Paul Fodor and Pearson Inc.
import static javafx.application.Application.launch; import
javafx.geometry.Insets;
import javafx.scene.control.RadioButton; import
javafx.scene.control.ToggleGroup; import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
public class RadioButtonDemo extends CheckBoxDemo {
@Override // Override the getPane() method in the super class protected
BorderPane getPane() {
BorderPane pane = super.getPane();
VBox paneForRadioButtons = new VBox(20);
paneForRadioButtons.setPadding(new Insets(5, 5, 5, 5));
paneForRadioButtons.setStyle("-fx-border-color: green"); RadioButton
rbRed = new RadioButton("Red");
RadioButton rbGreen = new RadioButton("Green"); RadioButton rbBlue = new
RadioButton("Blue");
paneForRadioButtons.getChildren().addAll(rbRed, rbGreen, rbBlue);
pane.setLeft(paneForRadioButtons);
ToggleGroup group = new ToggleGroup(); rbRed.setToggleGroup(group);
rbGreen.setToggleGroup(group); rbBlue.setToggleGroup(group);
rbRed.setOnAction(e -> {
if (rbRed.isSelected()) {
text.setFill(Color.RED);
}
});
116
8
6
67. rbGreen.setOnAction(e -> {
if (rbGreen.isSelected()) { text.setFill(Color.GREEN);
}
});
rbBlue.setOnAction(e -> {
if (rbBlue.isSelected()) { text.setFill(Color.BLUE);
}
});
return pane;
}
// the start method is inherited from the superclass
ButtonDemo public static void main(String[] args) {
launch(args);
}
}
87
8
7
68. TEXTFIELD
⚫A text field can be used to enter or display a
string.TextField is a subclass of TextInputControl.
88
8
8
69. (c) Paul Fodor and Pearson Inc.
import static javafx.application.Application.launch; import
javafx.geometry.Insets;
import javafx.geometry.Pos; import javafx.scene.control.Label;
import javafx.scene.control.TextField; import
javafx.scene.layout.BorderPane;
public class TextFieldDemo extends RadioButtonDemo{ @Override
protected BorderPane getPane() { BorderPane pane = super.getPane();
BorderPane paneForTextField = new BorderPane();
paneForTextField.setPadding(new Insets(5, 5, 5, 5));
paneForTextField.setStyle("-fx-border-color: green");
paneForTextField.setLeft(new Label("Enter a new message: "));
TextField tf = new TextField(); tf.setAlignment(Pos.BOTTOM_RIGHT);
paneForTextField.setCenter(tf); pane.setTop(paneForTextField);
tf.setOnAction(e -> text.setText(tf.getText())); return pane;
}
public static void main(String[] args) {
launch(args);
}
}119
8
9
71. COMBOBOX
⚫A combo box, also known as a choice list or drop-down list,
contains a list of items from which the user can choose.
91
9
1
72. LISTVIEW
⚫A list view is a component that performs basically
the same function as a combo box, but it enables the
user to choose a single value or multiple values.
92
9
2
73. (c) Paul Fodor and Pearson Inc.
import javafx.application.Application; import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.ListView; import javafx.scene.control.ScrollPane;
import javafx.scene.control.SelectionMode; import
javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import
javafx.scene.layout.FlowPane; import javafx.collections.FXCollections;
public class ListViewDemo extends Application {
// Declare an array of Strings for flag titles
private String[] flagTitles = {"United States of America", "Canada", "China",
"Denmark", "France", "Germany", "India"};
// Declare an ImageView array for the national flags private ImageView[]
ImageViews = {
new ImageView("image/us.gif"), new ImageView("image/ca.gif"), new
ImageView("image/china.gif"),
new ImageView("image/denmark.gif"),
new ImageView("image/fr.gif"),
new ImageView("image/germany.gif"), new ImageView("image/india.gif")
};
@Override
public void start(Stage primaryStage) {
ListView<String> lv = new ListView<>(FXCollections
.observableArrayList(flagTitles));
123 lv.setPrefSize(400, 400);
9
3
74. lv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
// Create a pane to hold image views FlowPane imagePane = new
FlowPane(10, 10); BorderPane pane = new BorderPane();
pane.setLeft(new ScrollPane(lv)); pane.setCenter(imagePane);
lv.getSelectionModel().selectedItemProperty().addListener( ov ->
{
imagePane.getChildren().clear();
for (Integer i: lv.getSelectionModel().getSelectedIndices()) {
imagePane.getChildren().add(ImageViews[i]);
}
});
Scene scene = new Scene(pane, 450, 170);
primaryStage.setTitle("ListViewDemo");
primaryStage.setScene(scene); primaryStage.show();
}
public static void main(String[] args) { launch(args);
}
}
94
9
4