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

Reference and Introduction

The document discusses graphical user interfaces (GUIs) in JavaFX. It provides an overview of GUI frameworks like AWT, Swing, and JavaFX. It explains how GUIs work by constructing components, rendering the GUI, checking for input, and responding to user input. Examples are given for creating simple JavaFX applications with buttons and displaying shapes on a pane. The document also discusses binding properties to center components when resizing a window.

Uploaded by

Honey A
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Reference and Introduction

The document discusses graphical user interfaces (GUIs) in JavaFX. It provides an overview of GUI frameworks like AWT, Swing, and JavaFX. It explains how GUIs work by constructing components, rendering the GUI, checking for input, and responding to user input. Examples are given for creating simple JavaFX applications with buttons and displaying shapes on a pane. The document also discusses binding properties to center components when resizing a window.

Uploaded by

Honey A
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Graphical User Interfaces

JavaFX GUI Basics, Event Programming


and GUI UI Controls
CSE260, Computer Science B: Honors
Stony Brook University
http://www.cs.stonybrook.edu/~cse260
GUI Examples

2
(c) Paul Fodor and Pearson Inc.
GUI
 Graphical User Interface (GUI)
 provides user-friendly human interaction
 Building Java GUIs require use of frameworks:
 AWT
 Swing
 JavaFX (part of Java since JSE 8, 2014) includes:
 GUI components
 Event Programming
 Graphics

3
(c) Paul Fodor and Pearson Inc.
How do GUIs work?
• They loop and respond to events

Construct GUI Components

Render GUI

Check to see if any input

Respond to user input

4
(c) Paul Fodor and Pearson Inc.
Example: a mouse click on a button
 Operating System recognizes mouse click
 determines which window it was inside
 notifies that program
 Program runs in loop
 checks input buffer filled by OS
 if it finds a mouse click:
 determines which component in the program
 if the click was on a relevant component
 respond appropriately according to handler
5
(c) Paul Fodor and Pearson Inc.
GUI Look vs. Behavior
 Look
physical appearance
custom component design
containment
layout management
 Behavior
interactivity
event programmed response
6
(c) Paul Fodor and Pearson Inc.
What does a GUI framework do for you?
 Provides ready made visible, interactive,
customizable components
 you wouldn’t want to have to code your own
window

7
(c) Paul Fodor and Pearson Inc.
JavaFX vs Swing and AWT
 Swing and AWT are replaced by the JavaFX platform for
developing rich Internet applications in JDK8 (2014)
 History:
 When Java was introduced (1996), the GUI classes were bundled in a
library known as the Abstract Windows Toolkit (AWT)
 AWT was prone to platform-specific bugs
 AWT was fine for developing simple graphical user interfaces, but not for
developing comprehensive GUI projects
 The AWT user-interface components were replaced by a more robust,
versatile, and flexible library known as Swing components (1997)
 Swing components are painted directly on canvases using Java code
 Swing components depend less on the target platform and use less of the native
GUI resource
 With the release of Java 8, Swing is replaced by a
completely new GUI platform: JavaFX
8
(c) Paul Fodor and Pearson Inc.
Basic Structure of JavaFX
Stage
Scene

Button

 javafx.application.Application is
the entry point for JavaFX applications
 JavaFX creates an application thread for running the
application start method, processing input events,
and running animation timelines.
 Override the start(Stage) method!
 javafx.stage.Stage is the top level JavaFX
container.
 The primary Stage is constructed by the platform.
 javafx.scene.Scene class is the container
for all content in a scene graph.
 javafx.scene.Node is the base class for
9 scene graph nodes.
(c) Paul Fodor and Pearson Inc.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;

public class MyFirstJavaFX extends Application {


@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Create a button and place it in the scene
Button btOK = new Button("OK");
Scene scene = new Scene(btOK, 200, 250);
primaryStage.setTitle("MyJavaFX"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}

/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}

10
(c) Paul Fodor and Pearson Inc.
// Multiple stages can be added beside the primaryStage
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;

public class MultipleStageDemo extends Application {


@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Create a scene and place a button in the scene
Scene scene = new Scene(new Button("OK"), 200, 250);
primaryStage.setTitle("MyJavaFX"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
Stage stage = new Stage(); // Create a new stage
stage.setTitle("Second Stage"); // Set the stage title
// Set a scene with a button in the stage
stage.setScene(new Scene(new Button("New Stage"), 100, 100));
stage.show(); // Display the stage
}

public static void main(String[] args) {


launch(args);
}
}
11
(c) Paul Fodor and Pearson Inc.
Panes, UI Controls, and Shapes

12
(c) Paul Fodor and Pearson Inc.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.control.Button;

public class ButtonInPane extends Application {

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


public void start(Stage primaryStage) {
// Create a scene and place a button in the scene
StackPane pane = new StackPane();
pane.getChildren().add(new Button("OK"));
Scene scene = new Scene(pane, 200, 50);
primaryStage.setTitle("Button in a pane"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}

public static void main(String[] args) {


launch(args);
}
}

13
(c) Paul Fodor and Pearson Inc.
Display a Shape

 Programming Coordinate Systems start from the left-upper


corner

14
(c) Paul Fodor and Pearson Inc.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene; Circle in a Pane
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.paint.Color;

public class ShowCircle extends Application {


@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Create a circle and set its properties
Circle circle = new Circle();
circle.setCenterX(100);
circle.setCenterY(100);
circle.setRadius(50);
circle.setStroke(Color.BLACK);
circle.setFill(null);
// Create a pane to hold the circle
Pane pane = new Pane();
pane.getChildren().add(circle);
// Create a scene and place it in the stage
Scene scene = new Scene(pane, 200, 200);
primaryStage.setTitle("ShowCircle"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}

/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}15
(c) Paul Fodor and Pearson Inc.
Binding Properties
 JavaFX introduces a new concept called binding property
that enables a target object to be bound to a source object.
 If the value in the source object changes, the target property is
also changed automatically.
 The target object is simply called a binding object or a binding
property.
 Resizing the window in the previous example would cover
the object:

16
(c) Paul Fodor and Pearson Inc.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.paint.Color;

public class ShowCircleCentered extends Application {


@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Create a pane to hold the circle
Pane pane = new Pane();
// Create a circle and set its properties
Circle circle = new Circle();
circle.centerXProperty().bind(pane.widthProperty().divide(2));
circle.centerYProperty().bind(pane.heightProperty().divide(2));
circle.setRadius(50);
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
pane.getChildren().add(circle); // Add circle to the pane
// Create a scene and place it in the stage
Scene scene = new Scene(pane, 200, 200);
primaryStage.setTitle("ShowCircleCentered"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}

/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
17 }
} (c) Paul Fodor and Pearson Inc.
The Image and ImageView Classes

24
(c) Paul Fodor and Pearson Inc.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.layout.HBox;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.geometry.Insets;

public class ShowImage extends Application {


@Override
public void start(Stage primaryStage) {
// Create a pane to hold the image views
Pane pane = new HBox(10);
pane.setPadding(new Insets(5, 5, 5, 5));
Image image = new Image("paul.jpg");
pane.getChildren().add(new ImageView(image));
ImageView imageView2 = new ImageView(image);
imageView2.setFitHeight(100);
imageView2.setFitWidth(100);
imageView2.setRotate(90);
pane.getChildren().add(imageView2);
Scene scene = new Scene(pane);
primaryStage.setTitle("ShowImage");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
25 }
(c) Paul Fodor and Pearson Inc.
}
Shapes
JavaFX provides many shape classes for drawing texts,
lines, circles, rectangles, ellipses, arcs, polygons, and
polylines.

35
(c) Paul Fodor and Pearson Inc.
Text

36
(c) Paul Fodor and Pearson Inc.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.geometry.Insets;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.FontPosture;
public class ShowText extends Application {
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
pane.setPadding(new Insets(5, 5, 5, 5));
Text text1 = new Text(20, 20, "Programming is fun");
text1.setFont(Font.font("Courier", FontWeight.BOLD,
FontPosture.ITALIC, 15));
pane.getChildren().add(text1);
Text text2 = new Text(60, 60, "Programming is fun\nDisplay text");
pane.getChildren().add(text2);
Text text3 = new Text(10, 100, "Programming is fun\nDisplay text");
text3.setFill(Color.RED);
text3.setUnderline(true);
text3.setStrikethrough(true);
pane.getChildren().add(text3);
Scene scene = new Scene(pane, 600, 800);
primaryStage.setScene(scene); primaryStage.show();
}
37 ...
} (c) Paul Fodor and Pearson Inc.
Line

38
(c) Paul Fodor and Pearson Inc.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.scene.paint.Color;
public class ShowLine extends Application {
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
Line line1 = new Line(10, 10, 10, 10);
line1.endXProperty().bind(pane.widthProperty().subtract(10));
line1.endYProperty().bind(pane.heightProperty().subtract(10));
line1.setStrokeWidth(5);
line1.setStroke(Color.GREEN);
pane.getChildren().add(line1);
Line line2 = new Line(10, 10, 10, 10);
line2.startXProperty().bind(pane.widthProperty().subtract(10));
line2.endYProperty().bind(pane.heightProperty().subtract(10));
line2.setStrokeWidth(5);
line2.setStroke(Color.GREEN);
pane.getChildren().add(line2);
Scene scene = new Scene(pane, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
39 }
(c) Paul Fodor and Pearson Inc.
Rectangle

40
(c) Paul Fodor and Pearson Inc.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import java.util.Collections;
public class ShowRectangle extends Application {
public void start(Stage primaryStage) {
Pane pane = new Pane();
Rectangle r1 = new Rectangle(25, 10, 60, 30);
r1.setStroke(Color.BLACK);
r1.setFill(Color.WHITE);
pane.getChildren().add(new Text(10, 27, "r1"));
pane.getChildren().add(r1);
Rectangle r2 = new Rectangle(25, 50, 60, 30);
pane.getChildren().add(new Text(10, 67, "r2"));
pane.getChildren().add(r2);
for (int i = 0; i < 4; i++) {
Rectangle r = new Rectangle(100, 50, 100, 30);
r.setRotate(i * 360 / 8);
r.setStroke(Color.color(Math.random(), Math.random(),
Math.random()));
r.setFill(Color.WHITE);
pane.getChildren().add(r);
}
Scene scene = new Scene(pane, 250, 150);
primaryStage.setScene(scene); primaryStage.show();
41 }
...// main (c) Paul Fodor and Pearson Inc.
Circle

42
(c) Paul Fodor and Pearson Inc.
Ellipse

radiusX radiusY
(centerX, centerY)

43
(c) Paul Fodor and Pearson Inc.
Arc radiusY length

startAngle

0 degree

radiusX
(centerX, centerY)

44
(c) Paul Fodor and Pearson Inc.
Polygon and Polyline

The getter and setter methods for property values and a getter for property
javafx.scene.shape.Polygon itself are provided in the class, but omitted in the UML diagram for brevity.

+Polygon() Creates an empty polygon.


+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>

45
(c) Paul Fodor and Pearson Inc.
Event Programming
 Procedural programming is executed in
procedural/statement order
 In event-driven programming, code is executed
upon activation of events
 Operating Systems constantly monitor events
 Ex: keystrokes, mouse clicks, etc…
 The OS:
 sorts out these events
 reports them to the appropriate programs
46
(c) Paul Fodor and Pearson Inc.
Where do we come in?
 For each control (button, combo box, etc.):
define an event handler
construct an instance of event handler
tell the control who its event handler is
 Event Handler?
code with response to event
a.k.a. event listener

47
(c) Paul Fodor and Pearson Inc.
Java’s Event Handling
 An event source is a GUI control
 JavaFX: Button, ChoiceBox, ListView, etc.

http://docs.oracle.com/javase/8/javafx/user-interface-tutorial/ui_controls.htm
 different types of sources:
 can detect different types of events
 can register different types of listeners (handlers)
48
(c) Paul Fodor and Pearson Inc.
Java’s Event Handling
 When the user interacts with a control
(source):
 an event object is constructed
 the event object is sent to all registered listener
objects
 the listener object (handler) responds as you
defined it to

49
(c) Paul Fodor and Pearson Inc.
Event Listeners (Event Handler)
 Defined by you, the application programmer
you customize the response
How?
 Inheritance & Polymorphism
 You define your own listener class
implement the appropriate interface
define responses in all necessary methods

50
(c) Paul Fodor and Pearson Inc.
Event Objects
 Contain information about the event
 Like what?
 location of mouse click
 event source that was interacted with
 etc.
 Listeners use them to properly respond
 different methods inside a listener object can
react differently to different types of interactions
51
(c) Paul Fodor and Pearson Inc.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
public class HandleEvent extends Application {
public void start(Stage primaryStage) {
HBox pane = new HBox(10);
Button btOK = new Button("OK");
Button btCancel = new Button("Cancel");
OKHandlerClass handler1 = new OKHandlerClass();
btOK.setOnAction(handler1);
CancelHandlerClass handler2 = new CancelHandlerClass();
btCancel.setOnAction(handler2);
pane.getChildren().addAll(btOK, btCancel);
Scene scene = new Scene(pane);
primaryStage.setScene(scene); primaryStage.show();
}…/*main*/}
class OKHandlerClass implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent e) {
System.out.println("OK button clicked");
}}
class CancelHandlerClass implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent e) {
52 System.out.println("Cancel button clicked");
(c) Paul Fodor and Pearson Inc.
}}
Handling GUI Events
 Source object: button.
 An event is generated by external user actions such as mouse movements,
mouse clicks, or keystrokes.
 An event can be defined as a type of signal to the program that
something has happened.
 Listener object contains a method for processing the event.

53
(c) Paul Fodor and Pearson Inc.
Event Classes

54
(c) Paul Fodor and Pearson Inc.
Event Information
 An event object contains whatever properties are
pertinent to the event:
 the source object of the event using the
getSource() instance method in the
EventObject class.
 The subclasses of EventObject deal with
special types of events, such as button actions,
window events, component events, mouse
movements, and keystrokes.
55
(c) Paul Fodor and Pearson Inc.
Selected User Actions and Handlers

56
(c) Paul Fodor and Pearson Inc.
The Delegation Model

57
(c) Paul Fodor and Pearson Inc.
ControlCircle program that uses two buttons to control the size of a circle
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.paint.Color; ...
import javafx.scene.shape.Circle;
public class ControlCircle extends Application {
private CirclePane circlePane = new CirclePane();
@Override
public void start(Stage primaryStage) {
HBox hBox = new HBox();
Button btEnlarge = new Button("Enlarge");
Button btShrink = new Button("Shrink");
hBox.getChildren().add(btEnlarge);
hBox.getChildren().add(btShrink);
btEnlarge.setOnAction(new EnlargeHandler());
BorderPane borderPane = new BorderPane();
borderPane.setCenter(circlePane);
borderPane.setBottom(hBox);
BorderPane.setAlignment(hBox, Pos.CENTER);
Scene scene = new Scene(borderPane, 200, 150);
58 primaryStage.setScene(scene); primaryStage.show();
} (c) Paul Fodor and Pearson Inc.
ControlCircle program that uses two buttons to control the size of a circle
// Inner Class
class EnlargeHandler
implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent e) {
circlePane.enlarge();
}
}
}
class CirclePane extends StackPane {
private Circle circle = new Circle(50);
public CirclePane() {
getChildren().add(circle);
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
}
public void enlarge() {
circle.setRadius(circle.getRadius() + 2);
}
public void shrink() {
circle.setRadius(circle.getRadius() > 2
? circle.getRadius() - 2 : circle.getRadius());
59
}
} (c) Paul Fodor and Pearson Inc.
Scene scene = new Scene(hBox, 300, 50);
primaryStage.setTitle("AnonymousHandlerDemo");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

67
(c) Paul Fodor and Pearson Inc.
Simplifying Event Handing Using
Lambda Expressions
 Lambda expression is a new feature in Java 8.
 Predefined functions for the type of the input.
 Lambda expressions can be viewed as an anonymous method
with a concise syntax.

btEnlarge.setOnAction( btEnlarge.setOnAction(e -> {


new EventHandler<ActionEvent>() { // Code for processing event e
@Override });
public void handle(ActionEvent e) {
// Code for processing event e
}
}
});

(a) Anonymous inner class event handler (b) Lambda expression event handler

68
(c) Paul Fodor and Pearson Inc.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
public class LambdaHandlerDemo extends Application {
@Override
public void start(Stage primaryStage) {
// Hold two buttons in an HBox
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.setAlignment(Pos.CENTER);
Button btNew = new Button("New");
Button btOpen = new Button("Open");
Button btSave = new Button("Save");
Button btPrint = new Button("Print");
hBox.getChildren().addAll(btNew, btOpen, btSave, btPrint);
btNew.setOnAction(e -> {System.out.println("Process New");});
btOpen.setOnAction(e -> {System.out.println("Process Open");});
btSave.setOnAction(e -> {System.out.println("Process Save");});
btPrint.setOnAction(e -> {System.out.println("Process Print");});
Scene scene = new Scene(hBox, 300, 50);
primaryStage.setScene(scene); Output:
primaryStage.show(); Process New
} Process Open
public static void main(String[] args) {
69 launch(args); }} Process Save
(c) Paul Fodor and Pearson Inc.
Process Print
Basic Syntax for a Lambda Expression
 The basic syntax for a lambda expression is either:
(type1 param1, type2 param2, ...) -> expression

or
(type1 param1, type2 param2, ...) -> { statements; }

 The data type for a parameter may be explicitly


declared or implicitly inferred by the compiler.
 The parentheses can be omitted if there is only one
parameter without an explicit data type.

70
(c) Paul Fodor and Pearson Inc.
MouseEvent

75
(c) Paul Fodor and Pearson Inc.
// Move the text with the mouse clicked
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
public class MouseEventDemo extends Application {
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
Text text = new Text(20, 20, "Programming is fun");
pane.getChildren().add(text);
text.setOnMouseDragged(e -> {
text.setX(e.getX());
text.setY(e.getY());
});
Scene scene = new Scene(pane, 300, 100);
primaryStage.setTitle("MouseEventDemo");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
76 } (c) Paul Fodor and Pearson Inc.
}
The KeyEvent Class

77
(c) Paul Fodor and Pearson Inc.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
public class KeyEventDemo extends Application {
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
Text text = new Text(20, 20, "A");
text.setFocusTraversable(true);
pane.getChildren().add(text);
text.setOnKeyPressed(e -> {
switch (e.getCode()) {
case DOWN: text.setY(text.getY() + 10); break;
case UP: text.setY(text.getY() - 10); break;
case LEFT: text.setX(text.getX() - 10); break;
case RIGHT: text.setX(text.getX() + 10); break;
default:
if (Character.isLetterOrDigit(e.getText().charAt(0)))
text.setText(e.getText());
}
});
Scene scene = new Scene(pane, 200, 200);
primaryStage.setTitle("KeyEventDemo");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
78
} (c) Paul Fodor and Pearson Inc.
}
The KeyCode Constants

79
(c) Paul Fodor and Pearson Inc.
import
Control Circle with Mouse and Key
javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.HBox;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class ControlCircleWithMouseAndKey extends Application {


private CirclePane circlePane = new CirclePane();

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


public void start(Stage primaryStage) {
// Hold two buttons in an HBox
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.setAlignment(Pos.CENTER);
Button btEnlarge = new Button("Enlarge");
Button btShrink = new Button("Shrink");
hBox.getChildren().add(btEnlarge);
hBox.getChildren().add(btShrink);

// Create and register the handler


btEnlarge.setOnAction(e -> circlePane.enlarge());
btShrink.setOnAction(e -> circlePane.shrink());

BorderPane borderPane = new BorderPane();


borderPane.setCenter(circlePane);
borderPane.setBottom(hBox);
BorderPane.setAlignment(hBox, Pos.CENTER);
80
(c) Paul Fodor and Pearson Inc.
// Create a scene and place it in the stage
Scene scene = new Scene(borderPane, 200, 150);
primaryStage.setTitle("ControlCircle"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage

circlePane.setOnMouseClicked(e -> {
if (e.getButton() == MouseButton.PRIMARY) {
circlePane.enlarge();
}
else if (e.getButton() == MouseButton.SECONDARY) {
circlePane.shrink();
}
});

scene.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.UP) {
circlePane.enlarge();
}
else if (e.getCode() == KeyCode.DOWN) {
circlePane.shrink();
}
});
}

public static void main(String[] args) {


launch(args);
}
}
81
(c) Paul Fodor and Pearson Inc.
Listeners for Observable Objects
 You can add a listener to process a value change in an observable
object: an instance of javafx.beans.Observable
 Every binding property is an instance of Observable.
 Observable contains the
addListener(InvalidationListener
listener) method for adding a listener.
 Once the value is changed in the property, a listener is notified.
 The listener class should implement the
InvalidationListener interface, which uses the
invalidated(Observable o) method to handle the
property value change.

82
(c) Paul Fodor and Pearson Inc.
Listeners for Observable Objects
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
public class ObservablePropertyDemo {
public static void main(String[] args) {
DoubleProperty balance = new SimpleDoubleProperty();
balance.addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
System.out.println("The new value is " +
balance.doubleValue());
}
});
balance.set(4.5);
}
}
Output:
83
(c) Paul Fodor and Pearson Inc.
The new value is 4.5
Control Nodes
 Input control nodes:

104
(c) Paul Fodor and Pearson Inc.

You might also like