Chapter 16 JavaFX UI Controls and Multimedia
Chapter 16 JavaFX UI Controls and Multimedia
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 1
Motivations
A graphical user interface (GUI) makes a system
user-friendly and easy to use. Creating a GUI
requires creativity and knowledge of how GUI
components work. Since the GUI components in
Java are very flexible and versatile, you can create
a wide assortment of useful user interfaces.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 3
Frequently Used UI Controls
Throughout this book, the prefixes lbl, bt, chk, rb, tf, pf, ta, cbo, lv,
scb, sld, and mp are used to name reference variables for Label,
Button, CheckBox, RadioButton, TextField, PasswordField,
TextArea, ComboBox, ListView, ScrollBar, Slider, and
MediaPlayer.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 4
Labeled
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 5
Label
The Label class defines labels.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 6
Label Example
This example display several labels with text and images
in the label.
LabelWithGraphic
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 7
public void start(Stage primaryStage) {
ImageView us = new ImageView(new Image("image/us.gif"));
Label lb1 = new Label("US\n50 States", us);
lb1.setStyle("-fx-border-color: green; -fx-border-width: 2");
lb1.setContentDisplay(ContentDisplay.BOTTOM);
lb1.setTextFill(Color.RED);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 8
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);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 9
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 10
Button Example
ButtonDemo
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 11
public class ButtonDemo extends Application {
protected Text text = new Text(50, 50, "JavaFX Programming");
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 12
Pane paneForText = new Pane();
paneForText.getChildren().add(text);
pane.setCenter(paneForText);
return pane;
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 14
CheckBox Example
CheckBoxDemo
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 15
public class CheckBoxDemo extends ButtonDemo {
@Override // Override the getPane() method in the super class
protected BorderPane getPane() {
BorderPane pane = super.getPane();
text.setFont(fontNormal);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 16
VBox paneForCheckBoxes = new VBox(20);
paneForCheckBoxes.setPadding(new Insets(5, 5, 5, 5));
paneForCheckBoxes.setStyle("-fx-border-color: green");
CheckBox chkBold = new CheckBox("Bold");
CheckBox chkItalic = new CheckBox("Italic");
paneForCheckBoxes.getChildren().addAll(chkBold, chkItalic);
pane.setRight(paneForCheckBoxes);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 18
RadioButton
Radio buttons, also known as option buttons, enable you to
choose a single item from a group of choices.
In appearance radio buttons resemble check boxes, but check
boxes display a square that is either checked or blank, whereas
radio buttons display a circle that is either filled (if selected) or
blank (if not selected).
To group radio buttons, you need to create an instance of
ToggleGroup and set a radio button's toggleGroup property to
join the group.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 19
RadioButton
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 20
RadioButton Example
RadioButtonDemo
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 21
public class RadioButtonDemo extends CheckBoxDemo {
@Override // Override the getPane() method in the super class
protected BorderPane getPane() {
BorderPane pane = super.getPane();
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 22
ToggleGroup group = new ToggleGroup();
rbRed.setToggleGroup(group);
rbGreen.setToggleGroup(group);
rbBlue.setToggleGroup(group);
rbRed.setOnAction(e -> {
if (rbRed.isSelected()) {
text.setFill(Color.RED);
}
});
rbGreen.setOnAction(e -> {
if (rbGreen.isSelected()) {
text.setFill(Color.GREEN);
}
});
rbBlue.setOnAction(e -> {
if (rbBlue.isSelected()) {
text.setFill(Color.BLUE);
}
});
return pane;
} Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 23
}
TextField
A text field can be used to enter or display a string. TextField is a
subclass of TextInputControl.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 24
TextField Example
When you move the cursor in the text field and press the
Enter key, it fires an ActionEvent.
TextFieldDemo
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 25
public class TextFieldDemo extends RadioButtonDemo {
@Override // Override the getPane() method in the super class
protected BorderPane getPane() {
BorderPane pane = super.getPane();
return pane;
}
} 26
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
TextArea
A TextArea enables the user to enter multiple lines of text.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 27
TextArea
TextArea provides scrolling, but often it is
useful to create a ScrollPane object to hold
an instance of TextArea and let ScrollPane
handle scrolling for TextArea.
You can place any node in a ScrollPane.
ScrollPane automatically provides vertical
and horizontal scrolling if the node is too
large to fit in the viewing area.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 28
TextArea Example
This example gives a program that displays
an image in a label, a title in a label, and a
text in a text area.
DescriptionPane TextAreaDemo
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 29
TextArea Example
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 30
public class DescriptionPane extends BorderPane {
/** Label for displaying an image and a title */
private Label lblImageTitle = new Label();
public DescriptionPane() {
// Center the icon and text and place the text under the icon
lblImageTitle.setContentDisplay(ContentDisplay.TOP);
lblImageTitle.setPrefSize(200, 100);
taDescription.setWrapText(true);
taDescription.setEditable(false);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 31
// Create a scroll pane to hold the text area
ScrollPane scrollPane = new ScrollPane(taDescription);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 33
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 34
ComboBox
ComboBox is defined as a generic class like
the ArrayList class.
The generic type T specifies the element
type for the elements stored in a combo
box.
ComboBox<String> cbo = new ComboBox<>();
cbo.getItems().addAll("Item 1", "Item 2", "Item 3", "Item 4");
cbo.setStyle("-fx-color: red");
cbo.setValue("Item 1");
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 35
ComboBox
ComboBox can fire an ActionEvent. Whenver an item is
selected, an ActionEvent is fired.
ObservableList is a subinterface of java.util.list. Therefore,
you can apply all the methods defined in List for an
ObservableList.
For convenience, JavaFX provides the static method
FXCollections.observableArrayList(arrayOfElements) for
creating an ObservableList from any array of elements.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 36
ComboBox Example
This example lets users view an image and a
description of a country's flag by selecting the
country from a combo box.
ComboBoxDemo
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 37
public class ComboBoxDemo extends Application {
// Declare an array of Strings for flag titles
private String[] flagTitles = {"Canada", "China", "Denmark",
"France", "Germany", "India", "Norway", "United Kingdom",
"United States of America"};
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 38
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Set text description
flagDescription[0] = "The Canadian national flag ...";
flagDescription[1] = "Description for China ... ";
flagDescription[2] = "Description for Denmark ... ";
flagDescription[3] = "Description for France ... ";
flagDescription[4] = "Description for Germany ... ";
flagDescription[5] = "Description for India ... ";
flagDescription[6] = "Description for Norway ... ";
flagDescription[7] = "Description for UK ... ";
flagDescription[8] = "Description for US ... ";
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 40
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 41
ListView
The getSelectionModel() method returns an
instance of SelectionModel, which contains the
methods for setting a selection model and
obtaining selected indices and items.
The selection mode is defined in one of the two
constants SelectionMode.MULTIPLE and
SelectionMode.SINGLE, which indicates whether
a single item or multiple items can be selected.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 42
Example: Using ListView
This example gives
a program that lets
users select
countries in a list
and display the flags
of the selected
countries in the
labels.
ListViewDemo
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 43
public class ListViewDemo extends Application {
// Declare an array of Strings for flag titles
private String[] flagTitles = {"Canada", "China", "Denmark",
"France", "Germany", "India", "Norway", "United Kingdom",
"United States of America"};
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 44
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
ListView<String> lv = new ListView<> (FXCollections.observableArrayList(flagTitles));
lv.setPrefSize(400, 400);
lv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
lv.getSelectionModel().selectedItemProperty().addListener(
ov -> {
imagePane.getChildren().clear();
for (Integer i: lv.getSelectionModel().getSelectedIndices()) {
imagePane.getChildren().add(ImageViews[i]);
}
});
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 46
Scroll Bar Properties
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 47
ScrollBar
When the user changes the value of the scroll bar,
it notifies the listener of the change.
– By default, the value is 100 for max, 0 for min.
You can register a listener on the scroll bar's
valueProperty for responding to this change.
Example:
ScrollBar sb = new ScrollBar();
sb.valueProperty().addListener(ov -> {
// To Do
});
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 48
Example: Using Scrollbars
This example uses
horizontal and vertical
scrollbars to control a
message displayed on a
panel. The horizontal
scrollbar is used to move
the message to the left or
the right, and the vertical
scrollbar to move it up and
down.
ScrollBarDemo
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 49
public void start(Stage primaryStage) {
Text text = new Text(20, 20, "JavaFX Programming");
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 50
// Listener for horizontal scroll bar value change
sbHorizontal.valueProperty().addListener(ov ->
text.setX(sbHorizontal.getValue() * paneForText.getWidth() /
sbHorizontal.getMax()));
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 51
Slider
Slider is similar to ScrollBar, but Slider has more properties and
can appear in many forms.
Slider lets the user graphically select a value by sliding a knob
within a bounded interval. The slider can show both major and
minor tick marks between them.
The number of pixels between the tick marks is specified by the
majorTickUnit and minorTickUnit properties.
Sliders can be displayed horizontally or vertically, with or
without ticks, and with or without labels.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 52
Slider
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 53
Example: Using Sliders
SliderDemo
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 54
public void start(Stage primaryStage) {
Text text = new Text(20, 20, "JavaFX Programming");
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 55
// Create a border pane to hold text and scroll bars
BorderPane pane = new BorderPane();
pane.setCenter(paneForText);
pane.setBottom(slHorizontal);
pane.setRight(slVertical);
slHorizontal.valueProperty().addListener(ov ->
text.setX(slHorizontal.getValue() * paneForText.getWidth()
/slHorizontal.getMax()));
slVertical.valueProperty().addListener(ov ->
text.setY((slVertical.getMax() - slVertical.getValue())
* paneForText.getHeight() / slVertical.getMax()));
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 56
Case Study: Bounce Ball
This example displays a bouncing ball. You can add a
slider to control the speed of the ball movement.
BouceBallSlider
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 57
public void start(Stage primaryStage) {
BallPane ballPane = new BallPane();
Slider slSpeed = new Slider();
slSpeed.setMax(20);
ballPane.rateProperty().bind(slSpeed.valueProperty());
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 58
Video and Audio
You can use the Media class to obtain the source of the media, the MediaPlayer
class to play and control the media, and the MediaView class to display the video.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 59
MediaPlayer
The MediaPlayer class playes and controls the media with properties such as
autoPlay, currentCount, cycleCount, mute, volume, and totalDuration.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 60
MediaView
The MediaView class is a subclass of Node that provides a view of the Media
being played by a MediaPlayer. The MediaView class provides the properties for
viewing the media.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 61
Example: Using Media
This example displays a
video in a view. You can use
the play/pause button to
play or pause the video and
use the rewind button to
restart the video, and use the
slider to control the volume
of the audio.
MediaDemo
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 62
public class MediaDemo extends Application {
private static final String MEDIA_URL =
"https://liveexample.pearsoncmg.com/common/sample.mp4";
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 63
Button rewindButton = new Button("<<");
rewindButton.setOnAction(e -> mediaPlayer.seek(Duration.ZERO));
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 64
HBox hBox = new HBox(10);
hBox.setAlignment(Pos.CENTER);
hBox.getChildren().addAll(playButton, rewindButton,
new Label("Volume"), slVolume);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 65
Case Study: National Flags and Anthems
This case study presents a program that displays a nation’s
flag and plays its anthem.
FlagAnthem
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 66
public class FlagAnthem extends Application {
private final static int NUMBER_OF_NATIONS = 7;
private final static String URLBase =
"https://liveexample.pearsoncmg.com/common";
private int currentIndex = 0;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 67
Button btPlayPause = new Button("||");
btPlayPause.setOnAction(e -> {
if (btPlayPause.getText().equals(">")) {
btPlayPause.setText("||");
mp[currentIndex].play();
}
else {
btPlayPause.setText(">");
mp[currentIndex].pause();
}
});
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 68
ImageView imageView = new ImageView(images[currentIndex]);
ComboBox<String> cboNation = new ComboBox<>();
ObservableList<String> items = FXCollections.observableArrayList
("Denmark", "Germany", "China", "India", "Norway", "UK", "US");
cboNation.getItems().addAll(items);
cboNation.setValue(items.get(0));
cboNation.setOnAction(e -> {
mp[currentIndex].stop();
currentIndex = items.indexOf(cboNation.getValue());
imageView.setImage(images[currentIndex]);
mp[currentIndex].play();
btPlayPause.setText("||");
});
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 69
HBox hBox = new HBox(10);
hBox.getChildren().addAll(btPlayPause,
new Label("Select a nation: "), cboNation);
hBox.setAlignment(Pos.CENTER);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 70