0% found this document useful (0 votes)
60 views57 pages

GUI JavaFx

Graphical user interfaces (GUIs) allow users to interact with applications using visual elements like buttons and text boxes rather than solely through text on the console. JavaFX is a Java library that allows developers to create rich GUIs. In JavaFX, a stage represents the application window, a scene holds GUI nodes, and nodes are organized in a scene graph structure. To create a JavaFX application, developers extend the Application class and override the start method to initialize stages and scenes containing layout containers and GUI controls.

Uploaded by

Ali Salo
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
60 views57 pages

GUI JavaFx

Graphical user interfaces (GUIs) allow users to interact with applications using visual elements like buttons and text boxes rather than solely through text on the console. JavaFX is a Java library that allows developers to create rich GUIs. In JavaFX, a stage represents the application window, a scene holds GUI nodes, and nodes are organized in a scene graph structure. To create a JavaFX application, developers extend the Application class and override the start method to initialize stages and scenes containing layout containers and GUI controls.

Uploaded by

Ali Salo
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 57

GUI – JavaFx

ITCS 114 Computer Programming II


Dr. Ali Alsaffar
Department of Computer Science
Console Interface vs Graphical User Interface

 When the interaction uses a screen and keyboard, it is called a Console Interface.

 When the user interaction uses picture-like tools such as buttons and textboxes, it is called a Graphical User
Interface (GUI).

Console Interface GUI

Dr. Ali Alsaffar 2


Graphical User Interfaces (1 of 3)

 Many Java applications use a Graphical User Interface or GUI (pronounced “gooey”).

GUI Application Design the UI by writing Java


Statements

User Interface
(UI) Design the UI by using Scene Builder (a
drag-and-drop tool) which provides the
structure of the user interface by an
XML-based language called FAXML,
Logic Code separate from the application logic of the
code.

Dr. Ali Alsaffar 3


Graphical User Interfaces (2 of 3)

 A GUI is a graphical window(s) that provides interaction with the user.

 A window in a GUI commonly consists of several controls that present data to the user
and/or allow interaction with the application.

 Some of the common GUI controls are buttons, labels, text fields, check boxes, and radio
buttons.
Labe TextFiel
l d

Button
Dr. Ali Alsaffar 4
Graphical User Interfaces (3 of 3)
Examples of events are clicking a
 Programs that operate in a GUI environment must be button, moving the mouse over a
control, pressing a key on the
event-driven. keyboard, etc.

 An event is an action that takes place within a


program, such as the clicking of a button.

 Part of writing a GUI application is creating event


listeners.

 An event listener is a method that automatically Clicking the button by the mouse
creates an Event object that is passed
executes when a specific event occurs. to the listener, then the listener is
executed.
Dr. Ali Alsaffar 5
Introduction to JavaFX (1 of 5)

 JavaFX is a Java library for developing rich applications that employ graphics.

 You can use it to create:


 GUI applications, as well as applications that display 2D and 3D graphics

 standalone graphics applications that run on your local computer

 applications that run from a remote server

 applications that are embedded in a Web page

Dr. Ali Alsaffar 6


Introduction to JavaFX (2 of 5)
Stage
 JavaFX uses a theater metaphor to describe the structure
of a GUI.
 A theater has a stage
 On the stage, a scene is performed by actors
 In JavaFX,
Stage
 the stage is an empty window
Scene
 The scene is a collection of GUI objects (controls) that are
contained within the window.
 You can think of the GUI objects as the actors that make up the
scene.
Dr. Ali Alsaffar 7
Introduction to JavaFX (3 of 5)

 In memory, the GUI objects in a scene are organized


Stage
as nodes in a scene graph, which is a tree-like
Scene
hierarchical data structure.

 The scene graph has three types of nodes:


 Root Node: There is only one root node, which is the
parent of all the other nodes in the scene graph.
 Branch Node: A node that can have other nodes as
children
 Leaf Node: A node that cannot have children

Dr. Ali Alsaffar 8


Introduction to JavaFX (4 of 5)

 The Label and the TextField are grouped in a horizontal box (HBox).

 The HBox and the Button are grouped in a vertical box (VBox).

Label HBox
root
node
Scene VBox

HBox

Label
VBox Button
TextField
TextField

Button
Dr. Ali Alsaffar 9
Introduction to JavaFX (5 of 5)

 The Application Class


 An abstract class that is the foundation of all JavaFX applications

 JavaFX applications must extend the Application class

 The Application class has an abstract method named start, which is the entry point
for the application
 Because the start method is abstract, you must override it

Dr. Ali Alsaffar 10


General Layout of a JavaFX Program

import javafx.application.Application;
 Various import statements import javafx.stage.Stage;
import javafx.scene.Scene;
Other import statements…
 A class that extends the
public class ClassName extends Application
Application class {
public static void main(String[] args)
{
 A main method // Launch the application.
launch(args);
}
 A start method
@Override
public void start(Stage primaryStage)
{
// Insert startup code here.
}
}

Dr. Ali Alsaffar 11


MyFirstGUI.java

Empty Window

Dr. Ali Alsaffar 12


Designing the UI

To design a GUI, you need to do the following:

1. Instantiate the UI controls (e.g., Label, Button, TextField, etc.)

2. Instantiate a container (e.g, HBox, VBox, GridPane, FlowPane, etc.)


Stage
and add the controls to the container. Container or Layout

3. Instantiate a scene and add the container Scene

to the scene as a root node.

4. Add the scene to the stage.


Controls

Dr. Ali Alsaffar 13


Creating Controls

 Process for creating a control

1. Import the class for the control from the necessary javafx package.
Example: import javafx.scene.control.Label;

2. Instantiate the class, calling the desired constructor.


Example: Label lblMessage = new Label("Hello World");

 Another example: Creating a Button

1. Import the Button class from the necessary javafx package:


import javafx.scene.control.Button;

2. Instantiate the class, calling the desired constructor:


Button btnMyButton = new Button("Click Me");
Dr. Ali Alsaffar 14
Layout Containers

 You use layout containers to arrange the positions of controls on the screen.
 JavaFX provides many layout containers.
 We will start with these:
 HBox: Arranges controls in a single horizontal row.
 VBox: Arranges controls in a single vertical column.
 GridPane: Arranges controls in a grid with rows and columns.

 The layout container classes are in the javafx.scene.layout package

Dr. Ali Alsaffar 15


Adding Controls to a Layout Container
VBo
x Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
Button btn3 = new Button("Button 3");

VBox vbox = new VBox(btn1, btn2, btn3);

Button btn1 = new Button("Button 1");


GridPane ...
Button btn6 = new Button("Button 6");
GridPane gridPane = new GridPane();

gridPane.add(btn1, 0, 0); // col, row


gridPane.add(btn2, 1, 0);
. . .
gridPane.add(btn6, 2, 1);
Dr. Ali Alsaffar 16
Creating a Scene

 To create a scene, you instantiate the Scene class in the


javafx.scene package

 Then, you add your root node to the scene.

 Example
// Create a Label control Instantiate the control (Label)
Label lblMessage = new Label("Hello World");

// Create an HBox container and add the label Instantiate the container (HBox)
HBox hbox = new HBox(lblMessage); and add the control (Label) to the
container.
// Create a Scene and add the HBox as the root node
Scene scene = new Scene(hbox); Instantiate the scene (Scene) and
add the container (HBox) to the
scene
Dr. Ali Alsaffar 17
Adding the Scene to the Stage

 Once you've created a Scene object, you add it to the application's stage.

 The stage is an instance of the Stage class from the javafx.stage package.

 You do not have to instantiate the Stage class, however. It is created automatically and
passed as an argument to the start method.

@Override
public void start(Stage primaryStage)
{
...
primaryStage.setScene(scene)
}

Dr. Ali Alsaffar 18


Example
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;

public class HelloWorld extends Application


{
public static void main(String[] args)
{
launch(args);
}

@Override
public void start(Stage primaryStage)
{
Label lblMessage = new Label("Hello World"); Make a Label control
VBox vbox = new VBox(lblMessage); Create a container Vbox and put the label in it
Scene scene = new Scene(vbox); Make the VBox the root node in the scene
primaryStage.setScene(scene); Set the scene to the stage
primaryStage.show(); Show the stage (display it)
}
}

Dr. Ali Alsaffar 19


Example (updated)
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;

public class HelloWorld extends Application


{
public static void main(String[] args)
{
launch(args);
}

@Override
public void start(Stage primaryStage)
{
Label lblMessage = new Label("Hello World");
VBox vbox = new VBox(lblMessage);
vbox.setAlignment(Pos.CENTER); Center-align the VBox
Scene scene = new Scene(vbox, 300, 100);
primaryStage.setScene(scene);
primaryStage.setTitle("Hello");
primaryStage.show();
Width Height
}
}
Dr. Ali Alsaffar 20
Displaying Images

 You need two JavaFX classes:


@Override
public void start(Stage primaryStage)
 The Image class, from the {
// Create an Image object.
javafx.scene.image package Image image = new Image("HotAirBalloon.jpg");
// Create an ImageView object.
 Use this class to load an image into ImageView imageView = new ImageView(image);

memory // Put the ImageView in an HBox.


HBox hbox = new HBox(imageView);

 The ImageView class, also from the // Create a Scene with the HBox as its root node.
Scene scene = new Scene(hbox);
javafx.scene.image package // Add the Scene to the Stage.
primaryStage.setScene(scene);
// Set the stage title.
 Use this class to create a node that primaryStage.setTitle("Hot Air Balloon");
// Show the window.
displays the image primaryStage.show();
}

Dr. Ali Alsaffar 21


More About HBox and VBox Containers (1 of 2)

 To add spacing between the items in an HBox or VBox:


HBox hbox = new HBox(10, label1, label2, label3); HBox hbox = new HBox(label1, label2, label3);
hbox.setSpacing(10);

Spacing VBox vbox = new VBox(button1, button2, button3);


VBox vbox = new VBox(20, button1, button2, button3); vbox.setSpacing(20);

Spacing

HBox space

VBox space

Dr. Ali Alsaffar 22


More About HBox and VBox Containers (2 of 2)

 Padding is space that appears around the inside edge of a


container. VBox vbox = new VBox(username, password, login);
 The HBox and VBox containers have a setPadding vbox.setPadding(new
vbox.setSpacing(20);
Insets(25,30,40,50));

method.
Padding
 You pass an Insets object as an argument to the 25

setPadding method. 20

 The Insets object specifies the number of pixels of 50


30
20
padding.
 The Insets class is in the javafx.geometry package. 40

hbox.setPadding(new Insets(10));

Dr. Ali Alsaffar 23


Example

 Design the following User Interface (UI):

HBox
Spacing between controls
is 10
VBox
VBox
Spacing between controls
Spacing between controls
is 10
is 10

VBox
Spacing between controls
is 10

Dr. Ali Alsaffar 24


The GridPane Layout Container (1 of 2)

 Arranges its contents in a grid with columns and rows.


 The columns and rows are identified by indexes.
 The GridPane class is in the javafx.scene.layout
package.
1. First, instantiate the GridPane class
GridPane gridPane = new GridPane();

2. Second, you add controls to the container using the add method
gridPane.add(control, column, row);

Dr. Ali Alsaffar 25


The GridPane Layout Container (2 of 2)

 By default, there is no space between the rows and columns in a GridPane.


 To add horizontal spacing between the columns in a GridPane, call the container's setHgap
method.
 To add vertical spacing between the rows in a GridPane, call the container's setVgap method.
Columns 0, 1
GridPane gridpane = new GridPane();
gridpane.setHgap(10); Padding

gridpane.setVgap(10);
Rows Vgap
0, 1, 2, 3
Vgap
 The GridPane container also has a setPadding method to set
Vgap
the padding around the container’s inside edge:
GridPane gridpane = new GridPane();
gridpane.setPadding(new Insets(10));
Hgap

Dr. Ali Alsaffar 26


GridPane Example
GridPane root = new GridPane();
root.setPadding(new Insets(20));
root.setHgap(15);
root.setVgap(15);
Columns 0, 1
Label labelTitle = new Label("Enter your user name and password!");
Label labelUserName = new Label("User Name");
TextField fieldUserName = new TextField();
Label labelPassword = new Label("Password");
PasswordField fieldPassword = new PasswordField();
Button loginButton = new Button("Login");
Paddin
root.add(labelTitle, 0, 0, 2, 1); // span two columns g
20 Rows
root.add(labelUserName, 0, 1); 0, 1, 2, 3
root.add(labelPassword, 0, 2);
root.add(fieldUserName, 1, 1);
root.add(fieldPassword, 1, 2);
root.add(loginButton, 1, 3);
Vga
GridPane.setHalignment(labelUserName, HPos.RIGHT); p
15
GridPane.setHalignment(fieldUserName, HPos.LEFT); Hga
GridPane.setHalignment(labelPassword, HPos.RIGHT); p
15
GridPane.setHalignment(fieldPassword, HPos.LEFT);
GridPane.setHalignment(loginButton, HPos.RIGHT);
Scene scene = new Scene(root, 300, 200);

Dr. Ali Alsaffar 27


Using Multiple Layout Containers

 To get the particular screen layout that you desire, you will sometimes have to nest layout
containers.

Dr. Ali Alsaffar 28


Handling Events

 An event is an action that takes place within a program,


such as the clicking of a button.
 When an event takes place, the control that is responsible
for the event creates an event object in memory.
 The event object contains information about the event.

 The control that generated the event object is know as


the event source.
 It is possible that the event source is connected to one or
more event listeners.
Dr. Ali Alsaffar 29
Event Objects

 Event objects are instances of the Event class (from the javafx.event package), or one
of its subclasses.

 For example, a Button click generates an ActionEvent object. ActionEvent is a


subclass of the Event class.

Dr. Ali Alsaffar 30


Commonly Used Event Classes
Event Class Package Description
Created when the user performs an action with a button or other component. Usually
this means that the user clicked the button, but the user can also invoke a button
ActionEvent javafx.event action by tabbing to the button and pressing the Enter key. This is the most
commonly used event class, as it represents the most common types of user-interface
events.

InputEvent javafx. Created when an event that results from user input, such as a mouse or key click,
scene.input occurs.

KeyEvent javafx. Created when the user presses a key on the keyboard. This event can be used to watch
scene.input for specific keystrokes entered by the user. (KeyEvent is a subclass of InputEvent.)
Created when the user does something interesting with the mouse,
MouseEvent javafx. such as clicking one of the buttons, dragging the mouse, or simply
scene.input moving the mouse cursor over another object. (MouseEvent is a
subclass of InputEvent.)

TouchEvent javafx. Created when a user initiates a touch event on a device that allows
scene.input touch input.
WindowEvent javafx.stage Created when the status of the window (stage) changes.

Dr. Ali Alsaffar 31


Event Handlers

 Event handlers are objects.


 You write event handler classes that implement the EventHandler interface (from the
javafx.event package).
 The EventHandler interface specifies a void method named handle that has a
parameter of the Event class (or one of its subclasses).
class ButtonClickHandler implements EventHandler<ActionEvent>
{
@Override
void handle(ActionEvent event)
{
// Write event handling code here.
}
}
Dr. Ali Alsaffar 32
Registering an Event Handler

 The process of connecting an event handler object to a control is called registering the event
handler.

 Button controls have a method named setOnAction that registers an event handler:
mybutton.setOnAction(new ButtonClickHandler());

 When the user clicks the button, the event handler object’s handle method will be executed.

Dr. Ali Alsaffar 33


The Three Steps to Handle a JavaFX event

1. Create an event source (such as Button, Label, TexField …)


 Example: Button btnClick = new Button("Login");

2. Create an event handler (implement EventHandler interface)


 Example: class ButtonClickHandler implements EventHandler<ActionEvent>
{
@Override
void handle(ActionEvent event)
{
// Write event handling code here.
}
}

3. Register the event handler with the event source


btnClick.setOnAction(new ButtonClickHandler());
 Example:
Dr. Ali Alsaffar 34
Event Handling Example (1 of 2)

Let's look at an  When the user clicks


application that initially the button, the screen
displays this screen: changes to:

Dr. Ali Alsaffar 35


Event Handling Example (2 of 2)
import javafx.application.Application; @Override
import javafx.stage.Stage; public void start(Stage primaryStage)
{
import javafx.scene.Scene;
// Create a Label and a Button.
import javafx.scene.layout.VBox; myLabel = new Label("Click the button to see a message.");
import javafx.scene.control.Label; Button myButton = new Button("Click Me");
import javafx.scene.control.Button;
import javafx.geometry.Pos; // Register an event handler.
import javafx.event.EventHandler; myButton.setOnAction(new ButtonClickHandler());
import javafx.event.ActionEvent;
// Put the Label and Button in a VBox with 10 pixels of spacing.
VBox vbox = new VBox(10, myLabel, myButton);
public class EventDemo extends Application vbox.setAlignment(Pos.CENTER);
{
// Label reference is defined as a // Create a Scene and display it.
// private data member in the class. Scene scene = new Scene(vbox, 300, 100);
primaryStage.setScene(scene);
// This way, the label is accessed by any
primaryStage.show();
// object and method in the class }

private Label myLabel; class ButtonClickHandler implements EventHandler<ActionEvent>


{
public static void main(String[] args) @Override
public void handle(ActionEvent event)
{
{
launch(args); myLabel.setText("Thanks for clicking the button!");
} }
}
}

Dr. Ali Alsaffar 36


Lambda Expressions as Event Handlers

 A functional interface is an interface that has one, and only one, abstract method.
 The EventHandler interface has only one abstract method is a functional interface.
 Consider to use lambda expression to implement functional interface because it is more concise than the code
for instantiating an inner class.
public class KiloConverter extends Application{ public class KiloConverter extends Application {
@Override ...
public void start(Stage primaryStage) { @Override
... public void start(Stage primaryStage){
// Register an event handler. ...
myButton.setOnAction(new ButtonClickHandler()); // Register an event handler.
... myButton.setOnAction(e -> btn_Clicked(e));
} ...
}
class ButtonClickHandler implements
EventHandler<ActionEvent>{ private void btn_Clicked(ActionEvent e)
@Override {
public void handle(ActionEvent event) { myLabel.setText(“You clicked he button!");
myLabel.setText(“You clicked he button!"); }
} ...
}
...

Dr. Ali Alsaffar 37


Double column operator (::) as Event Handlers (Optional)

 Also, consider to use double column operator (::) to implement functional interface.

public class KiloConverter extends Application public class KiloConverter extends Application {
{ ...
... @Override
@Override public void start(Stage primaryStage){
public void start(Stage primaryStage){ ...
... // Register an event handler.
// Register an event handler. myButton.setOnAction(this::btn_Clicked);
myButton.setOnAction(e -> btn_Clicked(e)); ...
... }
}
private void btn_Clicked(ActionEvent e)
private void btn_Clicked(ActionEvent e) {
{ myLabel.setText(“You clicked he button!");
myLabel.setText(“You clicked he button!"); }
} ...
...

Dr. Ali Alsaffar 38


Event Handling Example

 Write a JavaFx application that has two buttons and a label as shown in the below GUI.

230
75
Spacing 10

Padding
20

Label
Buttons

 The label is used as a counter.

 When the Add button is clicked the counter is increased by 1.

 When the Subtract button is clicked the counter is decreased by 1.

Dr. Ali Alsaffar 39


Reading Input with TextField Controls

 At runtime, the user can type text into a TextField control.


 The TextField class is in the javafx.scene.control package.
 To create an empty TextField:
TextField myTextField = new TextField(); TextField

 To retrieve the text that the user has typed into a TextField control, call the control’s
You getText
can supply method.
a default value, e.g.
 The method returns the value that has been entered, as a String. “0.0”
TextField(“0.0”)
 Example
String input;
input = myTextField.getText();

Dr. Ali Alsaffar 40


TextField Control Example

 Write a JavaFx application that converts a value from kilometers into miles. Design the following
User Interface (UI) for your application:

GridPane (3 rows, 2 columns)


Hgap = 10, Vgap = 10
Label Padding = 20

TextField
Button
Label

 When the user enters a value in the text field and clicks the Convert button, the application
displays the result using a label below the button.
Dr. Ali Alsaffar 41
Dr. Ali Alsaffar 42
RadioButton Controls (1 of 3)

 RadioButton controls allow the user to select one choice from several possible options.

 The RadioButton class is in the javafx.scene.control package.

RadioButton radio1 = new RadioButton("Choice 1");


RadioButton radio2 = new RadioButton("Choice 2");
RadioButton radio3 = new RadioButton("Choice 3");

Dr. Ali Alsaffar 43


RadioButton Controls (2 of 3)

 RadioButton controls are normally grouped together in a toggle group.


 Only one of the RadioButton controls in a toggle group may be selected
at any time.
ToggleGrou
p

 Clicking on a RadioButton selects it and automatically deselects any other RadioButton in


the same toggle group.
 To create a toggle group, you use the ToggleGroup class, which is in the
javafx.scene.control package:
ToggleGroup myToggleGroup = new ToggleGroup();
 After creating a ToggleGroup object, you call each RadioButton control’s setToggleGroup
method to add them to the ToggleGroup
Dr. Ali Alsaffar 44
RadioButton Controls (3 of 3)

Creating RadiuButtons Testing For An Option

// Create some RadioButtons


RadioButton radio1 = new RadioButton("Option 1");
 To determine whether a RadioButton is selected,
RadioButton radio2 = new RadioButton("Option 2");
RadioButton radio3 = new RadioButton("Option 3"); you call the RadioButton class’s isSelected()
// Create a ToggleGroup
method.
ToggleGroup radiuGroup = new ToggleGroup();
if (radio.isSelected())
// Add the RadioButtons to the ToggleGroup {
radio1.setToggleGroup(radiuGroup); // Code here execute if the radio
radio2.setToggleGroup(radiuGroup); // button is selected
radio2.setToggleGroup(radiuGroup); }
// Add the RadioButtons to a VBox.
VBox radioVBox = new VBox(10, radio1, radio2, radio3);  You can select a RadioButton in code with the
// Give the radioVBox some padding. RadioButton class’s setSelected() method:
radioVBox.setPadding(new Insets(30));
radio1.setSelected(true);

Dr. Ali Alsaffar 45


CheckBox Controls (1 of 3)

 CheckBox controls allow the user to make yes/no or on/off selections.

 The CheckBox class is in the javafx.scene.control package.

 Example. CheckBox choice1 = new CheckBox("Choice 1");


CheckBox choice2 = new CheckBox("Choice 2");
CheckBox choice3 = new CheckBox("Choice 3");

Dr. Ali Alsaffar 46


CheckBox Controls (2 of 3)

Creating CheckBox Testing For An Option

// Create some CheckBoxes


CheckBox choice1 = new CheckBox("Choice 1");
 To determine whether a CheckBox is selected, you
CheckBox choice2 = new CheckBox("Choice 2");
CheckBox choice3 = new CheckBox("Choice 3"); call the CheckBox class’s isSelected() method.
// Add the check boxes to a VBox.
VBox checkVBox = new VBox(10, choice1, choice2, choice3);
if (check1.isSelected())
// Give the checkBox some padding. {
checkVBox.setPadding(new Insets(30)); // Code here executes if the check
// box is selected.
}
 You can select a CheckBox in code with the
CheckBox class’s setSelected() method:
check1.setSelected(true);

Dr. Ali Alsaffar 47


Responding to RadioButton/CheckBox Clicks
// data members
 If you want an action to take place immediately RadioButton option1, option2;
when the user clicks a RadioButton/CheckBox @Override
public void start(Stage primaryStage)
control, register an ActionEvent handler with {
...
the control. // Create the RadioButtons.
option1 = new RadioButton("Salary < 500");
option2 = new RadioButton("Salary >= 500");
 The process is the same as with the Button
// Register an ActionEvent handler
control. option1.setOnAction(e -> radioButtonsClicked(e));
option2.setOnAction(e -> radioButtonsClicked(e));
...
}

private void radioButtonsClicked(ActionEvent e)


{
if (option1.isSelected())
// write code for option 1
else if (option2.isSelected())
// write code for option 1
}
Dr. Ali Alsaffar 48
RadioButton Control Example

 Write a JavaFx application that has two radio buttons and an image viewer.

 When the user clicks Flower radio button, the image viewer displays a flower image.

 When the user clicks the Sunset radio button, the image viewer displays a sunset image.

Dr. Ali Alsaffar 49


ComboBox Controls (1 of 4)
 A ComboBox presents a drop-down list of items that the user may select from.

 Use the ComboBox class to create a ComboBox control (javafx.scene.control package):

ComboBox<String> cmbBox = new ComboBox<>();

 Once you have created a ComboBox control, you are ready to add items to it:

cmbBox.getItems().addAll("Will", "Megan", "Amanda", "Tyler");

Dr. Ali Alsaffar 50


ComboBox Controls (2 of 4)

 Some of the ComboBox Methods


Method Description
getValue() Returns the item that is currently selected in the ComboBox.

setValue(value) Selects value in the ComboBox.


setVisibleRowCount(count) The count argument is an int. Sets the number of rows, or items, to display in the drop-down
list.

setEditable(value) The value argument is a boolean. If value is true, the ComboBox will be editable. If value is
false, the ComboBox will be uneditable.

show() Displays the drop-down list of items.


hide() Hides the drop-down list of items.
isShowing() Returns true or false to indicate whether the dropdown list is visible.

Dr. Ali Alsaffar 51


ComboBox Controls (3 of 4)

 You can use the ComboBox class’s getValue() method to get the item that is currently selected:
String selected = comboBox.getValue();
 If no item is selected in the ComboBox, the method will return null.

 To immediately perform an action when the user selects an item in a ComboBox, write an event
handler that responds to the ActionEvent:

cmbBox.setOnAction(event -> comboClicked(event));


...
private void comboClicked(ActionEvent event)
{
// Write event handling code here...
});

Dr. Ali Alsaffar 52


ComboBox Controls (4 of 4)

 By default, ComboBox controls are


uneditable
 The user cannot type input into the control; can
only select items from a drop-down list.
 An editable ComboBox allows the user to
select an item, or type input into a field that
is similar to a TextField.
 Use the setEditable method to make a
ComboBox editable:
ComboBox<String> cmbBox = new ComboBox<>();
cmbBox.setEditable(true);
cmbBox.getItems().addAll("England", "Scotland",
"Ireland", "Wales");

Dr. Ali Alsaffar 53


ComboBox Control Example (Distance Converter)

 Write a JavaFx application that converts a distance measure from kilometers to miles, and vice versa. Design
the below GUI for the application.

GridPane (3 rows, 2 columns)


Hgap = 10, Vgap = 10
Padding = 20

 The conversion is computed instantly while typing the distance value or selecting a distance unit (Kilometer
or Mile) from the combobox control.

 If the entered value is not numeric, change the input style to red over yellow and the error message to red as
an indication of invalid input.
Dr. Ali Alsaffar 54
The BorderPane Layout Container (1 of 2)

 The BorderPane layout container manages controls in


five regions.
 Only one object at a time may be placed into a
BorderPane region.
 You do not usually put controls directly into a
BorderPane region.
 Typically, you put controls into another type of layout
container, then you put that container into one of the
BorderPane regions.
Dr. Ali Alsaffar 55
The BorderPane Layout Container (1 of 2)

 The BorderPane class is in the javafx.scene.layout package.

 Summary of constructors:
Constructor Description
BorderPane() The no-arg constructor creates an empty
BorderPane container.

BorderPane(center) This constructor accepts one argument. The node that is


passed as the argument is placed in the BorderPane’s
center region.
BorderPane(center, top, right, bottom, left) This constructor accepts five nodes as arguments; one to
place in each region.

 The BorderPane class provides the following methods to add controls to specific regions:
 setCenter(), setTop(), setBottom(), setLeft(), setRight()

Dr. Ali Alsaffar 56


Dr. Ali Alsaffar 57

You might also like