0% found this document useful (0 votes)
317 views

Chapter 16 JavaFX UI Controls and Multimedia

This chapter introduces JavaFX UI controls and multimedia in detail. It discusses graphical user interfaces and how to create them using JavaFX components. The chapter objectives are to create interfaces using various controls like labels, buttons, checkboxes, radio buttons, text fields, scroll bars, sliders and play audio/video. It describes the base Labeled and ButtonBase classes that controls inherit properties from and provides examples of creating labels and buttons.

Uploaded by

Bhavik Dave
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
317 views

Chapter 16 JavaFX UI Controls and Multimedia

This chapter introduces JavaFX UI controls and multimedia in detail. It discusses graphical user interfaces and how to create them using JavaFX components. The chapter objectives are to create interfaces using various controls like labels, buttons, checkboxes, radio buttons, text fields, scroll bars, sliders and play audio/video. It describes the base Labeled and ButtonBase classes that controls inherit properties from and provides examples of creating labels and buttons.

Uploaded by

Bhavik Dave
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

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.

Previous chapters briefly introduced several GUI


components. This chapter introduces the
frequently used GUI components in detail.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 2
Objectives
 To create graphical user interfaces with various user-interface controls (§§16.2–16.11).
 To create a label with text and graphic using the Label class and explore properties in the abstract
Labeled class (§16.2).
 To create a button with text and graphic using the Button class and set a handler using the
setOnAction method in the abstract ButtonBase class (§16.3).
 To create a check box using the CheckBox class (§16.4).
 To create a radio button using the RadioButton class and group radio buttons using a ToggleGroup
(§16.5).
 To enter data using the TextField class (§16.6).
 To enter data in multiple lines using the TextArea class (§16.7).
 To select a single item using ComboBox (§16.8).
 To select a single or multiple items using ListView (§16.9).
 To select a range of values using ScrollBar (§16.10).
 To select a range of values using Slider and explore differences between ScrollBar and Slider
(§16.11).
 To view and play video and audio using the Media, MediaPlayer, and MediaView (§16.13).
 To develop a case study for showing the national flag and play anthem (§16.14).

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);

Label lb2 = new Label("Circle", new Circle(50, 50, 25));


lb2.setContentDisplay(ContentDisplay.TOP);
lb2.setTextFill(Color.ORANGE);

Label lb3 = new Label("Rectangle", 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);

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);

HBox pane = new HBox(20);


pane.getChildren().addAll(lb1, lb2, lb3, lb4, lb5);

// Create a scene and place it in the stage


Scene scene = new Scene(pane, 450, 150);
primaryStage.setTitle("LabelWithGraphic");
primaryStage.setScene(scene);
primaryStage.show();
}
}

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");

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);

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);

btLeft.setOnAction(e -> text.setX(text.getX() - 10));


btRight.setOnAction(e -> text.setX(text.getX() + 10));

return pane;
}

@Override // Override the start method in the Application class


public void start(Stage primaryStage) {
// Create a scene and place it in the stage
Scene scene = new Scene(getPane(), 450, 200);
primaryStage.setTitle("ButtonDemo"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 13
CheckBox
A CheckBox is used for the user to make a selection. Like Button,
CheckBox inherits all the properties such as onAction, text,
graphic, alignment, graphicTextGap, textFill, contentDisplay
from ButtonBase and Labeled.

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();

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);

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);

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
}
};
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 17
chkBold.setOnAction(handler);
chkItalic.setOnAction(handler);

return pane; // Return a new pane


}
}

The start method for this JavaFX program is defined in


ButtonDemo and inherited in this program.

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();

VBox paneForRadioButtons = new VBox(20);


paneForRadioButtons.setPadding(new Insets(5, 5, 5, 5));
paneForRadioButtons.setStyle
("-fx-border-width: 2px; -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);

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.

Type in a new text

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();

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;
}
} 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();

/** Text area for displaying text */


private TextArea taDescription = new TextArea();

public DescriptionPane() {
// Center the icon and text and place the text under the icon
lblImageTitle.setContentDisplay(ContentDisplay.TOP);
lblImageTitle.setPrefSize(200, 100);

// Set the font in the label and the text field


lblImageTitle.setFont(new Font("SansSerif", 16));
taDescription.setFont(new Font("Serif", 14));

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);

// Place label and scroll pane in the border pane


setLeft(lblImageTitle);
setCenter(scrollPane);
setPadding(new Insets(5, 5, 5, 5));
}

/** Set the title */


public void setTitle(String title) {
lblImageTitle.setText(title);
}

/** Set the image view */


public void setImageView(ImageView icon) {
lblImageTitle.setGraphic(icon);
}

/** Set the text description */


public void setDescription(String text) {
taDescription.setText(text);
}
} Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 32
public class TextAreaDemo extends Application {
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Declare and create a description pane
DescriptionPane descriptionPane = new DescriptionPane();

// Set title, text and image in the description pane


descriptionPane.setTitle("Canada");
String description = "The Canadian national flag ...";
descriptionPane.setImageView(new ImageView("image/ca.gif"));
descriptionPane.setDescription(description);

// Create a scene and place it in the stage


Scene scene = new Scene(descriptionPane, 450, 200);
primaryStage.setTitle("TextAreaDemo");
primaryStage.setScene(scene);
primaryStage.show();
}
}

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"};

// Declare an ImageView array for the national flags of 9 countries


private ImageView[] flagImage = {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"),
new ImageView("image/norway.gif"),
new ImageView("image/uk.gif"), new ImageView("image/us.gif")};

// Declare an array of strings for flag descriptions


private String[] flagDescription = new String[9];

// Declare and create a description pane


private DescriptionPane descriptionPane = new DescriptionPane();

// Create a combo box for selecting countries


private ComboBox<String> cbo = new ComboBox<>(); // flagTitles

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 ... ";

// Set the first country (Canada) for display


setDisplay(0);

// Add combo box and description pane to the border pane


BorderPane pane = new BorderPane();

BorderPane paneForComboBox = new BorderPane();


paneForComboBox.setLeft(new Label("Select a country: "));
paneForComboBox.setCenter(cbo);
pane.setTop(paneForComboBox);
cbo.setPrefWidth(400);
cbo.setValue("Canada");
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 39
ObservableList<String> items = FXCollections.observableArrayList(flagTitles);
cbo.getItems().addAll(items);
pane.setCenter(descriptionPane);

// Display the selected country


cbo.setOnAction(e -> setDisplay(items.indexOf(cbo.getValue())));

// Create a scene and place it in the stage


Scene scene = new Scene(pane, 450, 170);
primaryStage.setTitle("ComboBoxDemo");
primaryStage.setScene(scene);
primaryStage.show();
}

/** Set display information on the description pane */


public void setDisplay(int index) {
descriptionPane.setTitle(flagTitles[index]);
descriptionPane.setImageView(flagImage[index]);
descriptionPane.setDescription(flagDescription[index]);
}
}

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"};

// Declare an ImageView array for the national flags of 9 countries


private ImageView[] ImageViews = {
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"),
new ImageView("image/norway.gif"),
new ImageView("image/uk.gif"),
new ImageView("image/us.gif")
};

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);

// 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]);
}
});

// Create a scene and place it in the stage


Scene scene = new Scene(pane, 450, 170);
primaryStage.setTitle("ListViewDemo");
primaryStage.setScene(scene);
primaryStage.show();
}
} Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 45
ScrollBar
A scroll bar is a control that enables the user to select from a range of values. The
scrollbar appears in two styles: horizontal and vertical.

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");

ScrollBar sbHorizontal = new ScrollBar();


ScrollBar sbVertical = new ScrollBar();
sbVertical.setOrientation(Orientation.VERTICAL);

// Create a text in a pane


Pane paneForText = new Pane();
paneForText.getChildren().add(text);

// Create a border pane to hold text and scroll bars


BorderPane pane = new BorderPane();
pane.setCenter(paneForText);
pane.setBottom(sbHorizontal);
pane.setRight(sbVertical);

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()));

// Listener for vertical scroll bar value change


sbVertical.valueProperty().addListener(ov ->
text.setY(sbVertical.getValue() * paneForText.getHeight() /
sbVertical.getMax()));

// Create a scene and place it in the stage


Scene scene = new Scene(pane, 450, 170);
primaryStage.setTitle("ScrollBarDemo");
primaryStage.setScene(scene);
primaryStage.show();
}

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

Rewrite the preceding


program using the sliders
to control a message
displayed on a panel
instead of using scroll
bars.

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");

Slider slHorizontal = new Slider();


slHorizontal.setShowTickLabels(true);
slHorizontal.setShowTickMarks(true);

Slider slVertical = new Slider();


slVertical.setOrientation(Orientation.VERTICAL);
slVertical.setShowTickLabels(true);
slVertical.setShowTickMarks(true);
slVertical.setValue(100);

// Create a text in a pane


Pane paneForText = new Pane();
paneForText.getChildren().add(text);

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()));

// Create a scene and place it in the stage


Scene scene = new Scene(pane, 450, 170);
primaryStage.setTitle("SliderDemo");
primaryStage.setScene(scene);
primaryStage.show();
}
}

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());

BorderPane pane = new BorderPane();


pane.setCenter(ballPane);
pane.setBottom(slSpeed);

// Create a scene and place it in the stage


Scene scene = new Scene(pane, 250, 250);
primaryStage.setTitle("BounceBallSlider");
primaryStage.setScene(scene);
primaryStage.show();
}

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";

@Override // Override the start method in the Application class


public void start(Stage primaryStage) {
Media media = new Media(MEDIA_URL);
MediaPlayer mediaPlayer = new MediaPlayer(media);
MediaView mediaView = new MediaView(mediaPlayer);

Button playButton = new Button(">");


playButton.setOnAction(e -> {
if (playButton.getText().equals(">")) {
mediaPlayer.play();
playButton.setText("||");
} else {
mediaPlayer.pause();
playButton.setText(">");
}
});

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));

Slider slVolume = new Slider();


slVolume.setPrefWidth(150);
slVolume.setMaxWidth(Region.USE_PREF_SIZE);
slVolume.setMinWidth(30);
slVolume.setValue(50);
mediaPlayer.volumeProperty().bind(
slVolume.valueProperty().divide(100));

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);

BorderPane pane = new BorderPane();


pane.setCenter(mediaView);
pane.setBottom(hBox);

// Create a scene and place it in the stage


Scene scene = new Scene(pane, 650, 500);
primaryStage.setTitle("MediaDemo");
primaryStage.setScene(scene);
primaryStage.show();
}
}

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;

@Override // Override the start method in the Application class


public void start(Stage primaryStage) {
Image[] images = new Image[NUMBER_OF_NATIONS];
MediaPlayer[] mp = new MediaPlayer[NUMBER_OF_NATIONS];

// Load images and audio


for (int i = 0; i < NUMBER_OF_NATIONS; i++) {
images[i] = new Image(URLBase + "/image/flag" + i + ".gif");
mp[i] = new MediaPlayer(new Media(
URLBase + "/audio/anthem/anthem" + i + ".mp3"));
}

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);

// Create a pane to hold nodes


BorderPane pane = new BorderPane();
pane.setCenter(imageView);
pane.setBottom(hBox);

// Create a scene and place it in the stage


Scene scene = new Scene(pane, 350, 270);
primaryStage.setTitle("FlagAnthem");
primaryStage.setScene(scene);
primaryStage.show();
mp[currentIndex].play();
}
}

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 70

You might also like