0% found this document useful (0 votes)
5 views22 pages

JavaFX GUI Programming Essentials

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)
5 views22 pages

JavaFX GUI Programming Essentials

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

@NGUYỄN Thị Thu Trang, trangntt@[Link].

vn 2

Outline
1. JavaFX Overview
OBJECT-ORIENTED PROGRAMMING
2. MVC Architectural Pattern
10. GUI PROGRAMMING WITH JAVAFX
3. JavaFX Window Structure
Nguyen Thi Thu Trang 4. Binding Properties
trangntt@[Link]
5. Data-Driven UIs

1 2

3 4

Review: JavaFX vs. Swing Why JavaFX?


• JavaFX is a software platform for creating and • Additional consistent in its style than Swing
delivering desktop applications, as well as rich • Design GUI like Web apps with XML and CSS (FXML)
internet applications (RIAs) that can run across than doing in Java code
a wide variety of devices. • Save building time

• Rich Internet applications (RIA) are Web- • Integrate 3D graphics, charts, and audio, video, and
based applications that have some characteristics of embedded Website inside GUI
graphical desktop applications • Easy to develop Game/Media applications

• JavaFX is intended to replace Swing as the • Light-weight and hardware accelerated


standard GUI library for Java SE, but both will be • Contains WebView supported the popular WebKit
included for the foreseeable future. browser
• Introduce Website within JavaFX

3 4
5 6

Why JavaFX? (2) Outline


• Support stylish animations 1. JavaFX Overview
• Resembling fades, Rotations, Motion ways
• Custom animations with KeyFrame and Timeline 2. MVC Architectural Pattern
• Support for modern touch devices 3. JavaFX Window Structure
• Resembling scrolling, swipping, rotating and zooming…
4. Binding Properties
• Many eye-catching controls
• E.g. Collapsible Titled Pane 5. Data-Driven UIs
• Eventsare higher thought-out and additional
consistent

5 6

7 8

MVC Architectural Pattern MVC pattern


• Architectural Pattern 1. After seeing it on VIEW
• General and reusable solution to a commonly
2. Users use CONTROLLER
occurring problem in software architecture
within a given context 3. Manipulate data (Update,
• Model-View-Controller (MVC) modify, delete, ..), the data on
• Dividing the related program logic into three MODEL has been changed.
interconnected elements
4. Displaying the data of
• Separating internal representations of
MODEL on VIEW.
information from the ways information is
presented to and accepted from the user

7 8
9

Model-View-Controller Controller
- responds to events
- accesses model / view
• Model
- propagates data
• Manageing the data of the application, independent of Model and view
the user interface
• View View
Model
• Rendering presentation of the data (from model) in a - long term storage - tables to display
particular format to user - data members - forms to change
• Controller - domain logic - controls to listen for events
• Accepting and responding to the user input
• logic to process user inputs
• Performs interactions on the data model objects
Model-View-Controller
• Updating views and/or showing data on views
Should probably be Model-Controller-View

9 10

11 12

Records the widgets in the GUI,


MVC in JavaFX JavaFX View: FXML their visible attributes and their
relationship to each other

An XML vocabulary for


defining and arranging
JavaFX GUI controls without
writing any Java code

11 12
13 14

Building View: JavaFX Scene Builder JavaFX Controller: a Java class


• A GUIbuilder called SceneBuilder allows drag- • Can interact with UI controls of FXML
and-drop manipulation of widgets • Controller class name must be the same as
“fx:controller” attribute of the main panel in FXML
• Must declare UI control with name the same as the
attribute “fx:id” of that UI control in FXML
• An event handler for the view
• When the user interacts with a control, the control
generates an event
• Must provide event handling methods corresponding to
declarations in the FXML
(e.g. onAction=“#showDateTime”)

13 14

Controller: Java code 15 16

public class MyController implements Initializable {


@FXML
private Button myButton; Must be completed by Discussion
@FXML the programmer to
private TextField myTextField; bring the GUI to life • What are the benefits to separate the UI
(View) and the program logic (Controller)?
// When user click on myButton, this method will be called
public void showDateTime(ActionEvent event) {
[Link]("Button Clicked!");
Date now= new Date();
DateFormat df = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:[Link]");
// Model Data
String dateTimeString = [Link](now);
// Show in VIEW
[Link](dateTimeString);
}
}
15 16
18 19

Additional elements Outline


• A set of classes to describe the model, 1. JavaFX Overview
which is what the GUI allows the user to
2. MVC Architectural Pattern
interact with
3. JavaFX Window Structure
• A set of cascading style sheets (CSS files) 4. Binding Properties
to further secify “look-and-feel” 5. Data-Driven UIs

18 19

20

Basic Structure of JavaFX Swing? Scene graph


The top-level JavaFX container • A JavaFX user interface is
based on a scene graph,
which is a tree, much like an
HTML document

Container for all content

20 21
22 23

Basic Structure of JavaFX E.g. Show Date Time UI

22 23

24

24 25
27

FXMLLoader: load() method Exercise: Show current date time


• Uses the FXML file that represents the • Please create a JavaFX application to
app’s GUI to create the GUI’s scene graph show the current date time to a text field
• Returns a Parent (package [Link]) when the user click on a button with text
reference to the scene graph’s root node “Show Date Time”
• Initializes the controller’s instance
variables,
• Creates and registers the event handlers
for any events specified in the FXML

26 27

28 29

Panes, UI Controls, and Shapes The Color Class

28 29
30 31

The Font Class The Image Class

30 31

32 33

The ImageView Class Layout Panes


JavaFX provides many types of panes for organizing
nodes in a container.

32 33
34 35

FlowPane GridPane

ShowGridPane

Run

34 35

36 37

BorderPane HBox

36 37
38 39

VBox Shapes
JavaFX provides many shape classes for drawing texts,
lines, circles, rectangles, ellipses, arcs, polygons, and
polylines.

38 39

40 41

Text Text Example

40 41
42 43

Line Rectangle

42 43

44 45

Rectangle Example Circle

44 45
46 47

Ellipse Arc

radiusX radiusY
(centerX, centerY)

46 47

48 49

Arc Examples Polygon and Polyline

radiusY length

startAngle

0 degree

radiusX
(centerX, centerY)

–30° –50°
The getter and setter methods for property values and a getter for property
–20° 20°
[Link] itself are provided in the class, but omitted in the UML diagram for brevity.

(a) Negative starting angle –30° and (b) Negative starting angle –50° +Polygon() Creates an empty polygon.
negative spanning angle –20° and positive spanning angle 20° +Polygon(double... points) Creates a polygon with the given points.
+getPoints(): Returns a list of double values as x- and y-coordinates of the points.
ObservableList<Double>

48 49
50 51

Outline Binding properties


1. JavaFX Overview • JavaFX introduces a new concept called binding
property that enables a target object to be bound
2. MVC Architectural Pattern to a source object
3. JavaFX Window Structure • If the value in the source object changes, the
target property is also changed automatically
4. Binding Properties
• The target object is simply called a binding object
5. Data-Driven UIs or a binding property

50 51

52 53

Example: Binding Properties Exercise: How to bind properties for the


below application?
Unidirectional Binding
[Link]().bind([Link]());
- text1 changes, lable1 changes correspondingly
- label1 changes, text1 does not change

Bidirectional Binding
[Link]().
bindBidirectional([Link]());

- text1 changes, text2 changes correspondingly


- text2 changes, text1 changes correspondingly

52 53
54 55

public class ShowCircleCentered extends Application {


public void start(Stage primaryStage) {
Display a Shape // Create a pane to hold the circle
Pane pane = new Pane();
Circle circle = new Circle();
This example displays a circle in the center of the
[Link]().bind([Link]().divide(2));
pane. [Link]().bind([Link]().divide(2));
[Link](50);
x
Y Axis [Link]([Link]);
(0, 0) X Axis
[Link]([Link]);
[Link]().add(circle); // Add circle to the pane
y
(x, y)
(0, 0) // Create a scene and place it in the stage
X Axis
Java Conventional Scene scene = new Scene(pane, 200, 200);
Coordinate Coordinate [Link]("ShowCircleCentered");
System System
Y Axis [Link](scene);
[Link]();
}
public static void main(String[] args) {
launch(args);
}
} Binding Properties
54 55

Example: ColorChooser Building the GUI


• Step 1: Adding a GridPane
• Drag a GridPane from the Library window’s Containers
section onto Scene Builder’s content panel
• Step 2: Configuring the GridPane
• This app’s GridPane requires four rows and four
columns
• Use the techniques you’ve learned previously to add
two columns and one row to the GridPane
• Set the GridPane’s Hgap and Padding properties to 8 to
inset the GridPane from the stage’s edges and to
provide space between its columns
© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

56 57
Building the GUI (cont.) Building the GUI (cont.)
• Step 3: Adding the Controls • Step 4: Configuring the Sliders
• Add the Labels, Sliders, TextFields, a Circle and a • For the red, green and blue Sliders, set the Max
Rectangle to the GridPane—Circle and Rectangle are properties to 255 (the maximum amount of a given color
located in the Scene Builder Library’s Shapes section in the RGBA color scheme)
• When adding the Circle and Rectangle, place both into • For the alpha Slider, set its Max property to 1.0 (the
the rightmost column’s first row maximum opacity in the RGBA color scheme).
• Be sure to add the Circle before the Rectangle so that it • Step 5: Configuring the TextFields
will be located behind the rectangle in the layout • Set all of the TextField’s Pref Width properties to 50.
• Set the text of the Labels and TextFields as shown and
set all the appropriate fx:id properties as you add each
control.

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

58 59

Building the GUI (cont.) Building the GUI (cont.)


• Step 6: Configuring the Rectangle • Step 8: Configuring the Rows
• Set all four columns’ Pref Height properties to
• Setthe Rectangle’s Width and Height USE_COMPUTED_SIZE so that the rows are only as tall as their
properties to 100, then set its Row Span content
property to Remainder so that it spans all four • Step 9: Configuring the Columns
rows. • Set all four columns’ Pref Width properties to
USE_COMPUTED_SIZE so that the columns are only as wide as
• Step 7: Configuring the Circle their content
• For the leftmost column, set the Halignment property to RIGHT
• Set the Circle’s Radius property to 40, then set • For the rightmost column, set the Halignment property to CENTER.
its Row Span property to Remainder so that it • Step 10: Configuring the GridPane
spans all four rows. • Set the GridPane’s Pref Width and Pref Height properties to
USE_COMPUTED_SIZE so that it sizes itself, based on its
contents
© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

60 61
ColorChooser Main Application

Building the GUI (cont.)


• Step 11: Specifying the Controller Class’s Name
• To ensure that an object of the controller class is
created when the app loads the FXML file at runtime,
specify ColorChooserController as the controller class’s
name in the FXML file as you’ve done previously.
• Step 12: Generating a Sample Controller Class
• Select View > Show Sample Controller Skeleton, then
copy this code into a [Link] file
and store the file in the same folder as
[Link]

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

62 63

ColorChooserController ColorChooserController (cont.)

64 65
ColorChooserController (cont.) ColorChooserController (cont.)

66 67

ColorChooserController Class (cont.) ColorChooserController Class (cont.)

• Property-to-Property Bindings Property-to-Property Bindings (cont.)


• Lines 31–38 set up property bindings between a • Each TextField has a text property that’s returned by its
textProperty method as a StringProperty (package
Slider’s value and the corresponding Text-Field’s [Link])
text so that changing a Slider updates the • StringProperty method bind receives an
corresponding TextField ObservableValue as an argument
• Consider lines 31–32, which bind the redSlider’s • When the ObservableValue changes, the bound property
valueProperty to the redText-Field’s textProperty: updates accordingly
• [Link]().bind( • In this case the ObservableValue is the result of the
[Link]().asString("%.0f")); expression
[Link]().asString("%.0f")

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

68 69
ColorChooserController Class (cont.) ColorChooserController Class (cont.)
Property-to-Property Bindings (cont.) Property Listeners
• Slider’s valueProperty method returns the Slider’s • To perform an arbitrary task when a property’s value
value property as a DoubleProperty—an observable changes, register a property listener
double value • Lines 41–80 register property listeners for the Sliders’
• Because the TextField’s text property must be bound to a value properties
String, we call DoubleProperty method asString, • Consider lines 41–50, which register the ChangeListener
which returns a StringBinding object (an that executes when the user moves the redSlider’s thumb
ObservableValue) that produces a String representation
• Each ChangeListener stores the int value of the
of the DoubleProperty
newValue parameter in a corresponding instance variable,
• This version of asString receives a format-control String then calls the colorRectangle’s setFill method to
specifying the DoubleProperty’s format change its color, using Color method rgb to create the new
Color object
© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

70 71

72

Outline Data-Driven GUIs with JavaFX Collections

1. JavaFX Overview • JavaFX provides a comprehensive model for


allowing GUIs to interact with data, e.g. edit and
2. MVC Architectural Pattern display data
3. JavaFX Window Structure • FXCollections: Creating and manipulating
observable collections
4. Binding Properties
• Example: List
5. Data-Driven UIs • ListView: UI component
• ObservableList: Can be observed by corresponding UI
components, e.g. ListView
• If you make changes to an ObservableList, its
observer will automatically be notified of those changes
© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

72 73
Cover Viewer application ListView and ObservableList
• Binds a list of Book objects to a ListView • ListView control:
Display a collection of book titles
• When the user selects an item in the ListView, the • Bind an ObservableList object to the ListView
corresponding Book’s cover image is displayed in an
ImageView. • If you make changes to an ObservableList, its observer
(the ListView in this app) will automatically be notified of
those changes
• Property listener to display the correct image
when the user selects an item from the
ListView—in this case, the property that changes
is the selected item

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

74 75

© Copyright 1992-2018 by Pearson Education, Inc. All Rights


Reserved.

Building the GUI (cont.)

Adding and Configuring the Controls


• Using the techniques you learned previously, create a
BorderPane
• In the left area, place a ListView control, and in the center
area, place an ImageView control
• For the ListView, set the following properties:
• Margin—8 (for the right margin) to separate the ListView from the
ImageView
• Pref Width—200
• Max Height—MAX_VALUE
• Min Width, Min Height, Pref Height and Max Width—
USE_COMPUTED_SIZE

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

76 77
Building the GUI (cont.) Building the GUI (cont.)

Adding and Configuring the Controls (cont.) Specifying the Controller Class’s Name
• For the ImageView, set the Fit Width and Fit Height • To ensure that an object of the controller class is created
properties to 370 and 480, respectively when the app loads the FXML file at runtime, specify
• To size the BorderPane based on its contents, set its Pref CoverViewerController as the controller class’s name in
Width and Pref Height to USE_COMPUTED_SIZE the FXML file as you’ve done previously.
• Also, set the Padding property to 8 to inset the BorderPane Generating a Sample Controller Class
from the stage. • Select View > Show Sample Controller Skeleton, then copy this
code into a [Link] file and store
the file in the same folder as [Link]

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

78 79

80 81
CoverViewerController Class (cont.)

@FXML Instance Variables


• Lines 14–15 declare the controller’s @FXML instance variables
• In this case, the ListView displays Book objects
• Class Book contains three String instance variables with set/get
methods:
• title—the book’s title.
• thumbImage—the path to the book’s thumbnail image (used in the next
example).
• largeImage—the path to the book’s large cover image
• The class also provides a toString method that returns the
Book’s title and a constructor that initializes the three instance
variables
• Copy [Link] from this chapter’s examples folder into the
folder that contains [Link], [Link]
and [Link]

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

82 83

CoverViewerController Class (cont.) CoverViewerController Class (cont.)

Instance Variable books Initializing the books ObservableList


• Lines 18–19 define the books instance variable as an • Lines 24–37 in method initialize create and add Book
ObservableList<Book> and initialize it by calling objects to the books collection
FXCollections static method observableArrayList • Line 38 passes this collection to ListView method
• This method returns an empty collection object (similar to setItems, which binds the ListView to the
an ArrayList) that implements the Observable-List ObservableList
interface • This data binding allows the ListView to display the Book
objects automatically
• By default, the ListView displays each Book’s String
representation

© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

84 85
CoverViewerController Class (cont.) CoverViewerController Class (cont.)

Listening for ListView Selection Changes Listening for ListView Selection Changes (cont.)
• To synchronize the book cover that’s being displayed with the • ListView method getSelectionModel returns a
currently selected book, we listen for changes to the ListView’s MultipleSelectionModel object
selected item • In this example, MultipleSelectionModel’s
• By default a ListView supports single selection selectedItemProperty method returns a
• ListViews also support multiple selection ReadOnlyObjectProperty<Book>
• Selection is managed by the ListView’s • Corresponding ChangeListener receives as oldValue and
MultipleSelectionModel (a subclass of SelectionModel newValue the previously selected and newly selected Book
from package [Link] objects, respectively
• Contains observable properties and various methods for manipulating the • Lines 47–48 use newValue’s large image path to initialize a new
corresponding ListView’s items
Image (package [Link])—this loads the image
• To respond to selection changes, you register a listener for the from that path
MultipleSelectionModel’s selectedItem property (lines 41–
• We then pass the new Image to the coverImageView’s
51) setImage method to display the Image
© Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

86 87

88

More examples/tutorials
• [Link]
• [Link]

88

You might also like