CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture VI JavaFX Basics In...
Author: Laurel Hoover
1 downloads 3 Views 4MB Size
CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department

Lecture VI JavaFX Basics

Introduction

Introduction ❂

JavaFX is a new framework for developing GUI (Graphical User Interface) Applications.



The JavaFX API is a great example of how object oriented principles can be applied.



This week we will learn how to develop GUI projects using layout panes, buttons, labels, text fields, colors, fonts, images, image views, and shapes.

JavaFX vs Swing vs AWT

JavaFX vs Swing vs AWT ❂



AWT (Abstract Windows Toolkit) −

first framework created for developing GUI apps in Java



only good for simple interfaces



prone to platform specific bugs



replaced by Swing

Swing −

more robust, versatile, and flexible



components are painted directly on canvases using Java code



less dependent on platform specific operations



will be completely replaced by JavaFX



Swing is essentially dead, no further updates.

JavaFX vs Swing vs AWT ❂

JavaFX −

incorporates modern GUI technologies to enable the development of rich Internet Applications (RIA)



RIAs are web apps designed to deliver the same features and functions normally associated with desktop applications.



JavaFX apps can run seemlessly on a desktop or from a Web browser



provides multi-touch support for touch-enabled devices such as tablets and smartphones



has built in 2D and 3D animation support, video and audo playback, runs as a stand-alone application or from a browser.



Simpler to learn than AWT or Swing

Basic Structure of a JavaFX Program

Basic Structure of a JavaFX Program ❂

Every JavaFX program is defined in a class which extends javafx.application.Application



Just extend the Application class and you can start making GUI programs.

MyJavaFX.java ❂

This program displays a window with a simple button on it.



line 22: the Application.launch(args) method is a static method defined in the Application class. −

if you run this program from the command line main is not needed.



some IDEs may need main to launch the application due to limited JavaFX support (such as Eclipse)

MyJavaFX.java ❂

line 8: the Driver class of your program needs to override the start method of Application. public void start(Stage primaryStage)



start() method −

usually used to place UI controls in a scene, and display the scene in a stage



Line 10: creates a Button object and places it in a Scene object



A Scene object can be created using Scene(node, width, height)

MyJavaFX.java ❂

A Stage object is a window −

primary stage a Stage object automatically created by the JVM when the application is launched

MultipleStageDemo.java

Panes, UI Controls and Shapes

Panes, UI Controls, and Shapes ❂

Panes, UI controls, and shapes, are all subtypes of the Node class.



node: visual components such as shapes, images, UI controls, or even a pane



pane: a container class which helps to automatically layout a node in a desired location and size. −

nodes are placed inside of a pane and then the pane is placed into a scene



shape: text, line, circle, ellipse, rectangle, arc, polygon, polyline, etc.



UI control: a label, button, checkbox, radio button, text field, text area, etc.

JavaFX Class Hierarchy ❂

The relationship between a Stage, Scene, Node, Control, and Pane is shown on the next slide.



A Scene can contain a Control or Pane, but not a Shape or ImageView



A Pane can contain any subtype of Node



A Scene can be created with:





Scene(Parent, width, height)



Scene(Parent) (dimensions are automatically decided)

Every subclass of Node has a no-arg constructor for creating a default node.

JavaFX Class Hierarcy

ButtonInPane.java

ButtonInPane.java ❂



line 11: program creates a StackPane −

StackPane places nodes in the center of the pane on top of each other.



StackPane respects a node's preferred size (it does not change the size of the components to fit the window)

line 12: adds a button as a child of the pane −

getChildren() returns an instance of ObservableList



ObservableList is a lot like an ArrayList for storing collections of elements



add(e) adds an element to the list

ShowInCircle.java

ShowInCircle.java ❂

line 12: creates a Circle



lines 13-14: set the center to be (100, 100) −

also center of Scene, since size of Scene is 200 x 200



all measurements are in pixels



line 16: stroke color set to black (line color)



line 17: fill color set to white (color to fill the shape) −

color could be null



line 20: creates a Pane, puts circle in pane



line 24: Pane is placed in the Scene



line 26: Scene is set in the Stage



NOTE: circle is centered as long as you do not resize the window. The next section will show how to fix this

JavaFX Coordinate System ❂

the upper left corner of a Pane or Scene is used as (0,0) in the Java coordinate system.



does not use the conventional coordinate system where (0,0) is the center of the Pane or Scene

Layout Panes

Layout Panes ❂

JavaFX provides various layout panes to automatically lay out nodes.

Layout Panes - FlowPane ❂

Arranges the nodes in the pane horizontally from left to right, or vertically from top to bottom in the order that the nodes were added to the pane.



If a row or column is filled, and new row or column is started.



Constants: −

Orientation.HORIZONTAL (place the nodes horizontally)



Orientation.VERTICAL (place the nodes vertically)



FlowPane has data fields alignment, orientation, hgap, and vgap which are binding properties



Each of the binding properties has a getter method (getHgap()) which returns its value, a setter methods (setHgap()) for setting the value, and a getter that returns the property itself (hGapProperty())

Layout Panes - FlowPane

Layout Panes - FlowPane ❂

See: ShowFlowPane.java

Layout Panes - GridPane ❂

Arranges nodes in a grid (matrix) formation, nodes are placed in the specified row and indicies.



See: ShowGridPane.java

Layout Panes - BorderPane ❂



Can place nodes in five regions: −

top



bottom setBottom(node)



left

setLeft(node)



right

setRight(node)



center

setCenter(node)

setTop(node)

See Code: ShowBorderPane.java

Layout Panes - BorderPane

HBox and VBox ❂

HBox lays out its children in a single row.



VBox lays out its children in a single vertical column



Recall that LayoutPanes use multiple rows and columns where as HBox and VBox use only a single column.



See Code: ShowHBoxVBox.java

Property Binding

Property Binding ❂



property binding: enables a target object to be bound to a source object −

target object is called the binding object or binding property



source object is called a bindable object or observable object

A change to the source object will be automatically reflected in the target object.

ShowCircleCentered.java

ShowCircleCentered.java ❂

same as the previous example, except binds circle's centerX and centerY properties to half of pane's width and height.



circle.centerXProperty() returns centerX



pane.widthPropery() returns width



both centerX and width are binding properties of the DoubleProperty type



all of the number binding property classes contain add, subtract, multiple, and divide methods for basic math operations and return a new observable property



pane.widthProperty().divide(2) returns a new observable property that represents half of the pane's width



since centerX is bound to width.divide(2), when pane's width is changed, centerX automatically updates itself to match pane's width / 2

Property Binding ❂

Circle class has a centerX property for representing the x-coordinate of the circle. −



can be used as both target and source in property binding (as can many other JavaFX class properties)

A target "listens" for changes to the source and automatically updates itself once a chance is made in the source.

The bind() Method ❂

To bind a source to a target use the bind method: target.bind(source);



bind() is defined in javafx.beans.property.Property interface. −



a binding property is an instance of Property

a source object is an instance of javafx.beans.value.ObservableValue −

an ObservableValue is an entity that wraps a value and allows to observe the value for changes.

Primitive Types and Strings ❂

JavaFX defines binding properties for primitive types and strings



DoubleProperty, FloatProperty, LongProperty, IntegerProperty, BooleanProperty, StringProperty −

these are all subtypes of ObservableValue so they can also be used as source objects for binding

Getters and Setters for Binding Properties ❂

By convention, each binding property (i.e. centerX) in a JavaFX class has a getter (getCenterX()) and a setter (setCenterX(double)).



There is also a getter for the property itself.





The naming convention for this method is the property name followed by the word Property



Example: the property getter method for centerX is centerXProperty()

getCenterX() is a value getter method −

returns a double value



setCenterX() is a value setter method



centerXProperty() is a property getter method −

returns an object of the DoubleProperty type

Getters and Setters for Property Binding

BindingDemo.java

BindingDemo.java ❂



line 6: creates an instance of DoubleProperty −

uses SimpleDoubleProperty because numeric property classes are abstract.



SimpleProperty subclasses are concrete subclasses (substitute with a type i.e. Double, Integer, Boolean, etc.)

line 8: binds d1 with d2 so values of d1 and d2 are the same −



any changes to d2 will also update d1

line 11: changes the value of d2

Unidirectional and Bidirectional Binding ❂

unidirectional binding: binding in only one direction, only changes in the source property will change the target property, changes to target will NOT change the source −



example: changes to d2 will change d1, changes to d1 will not change d2

bidirectional binding: binding in two directions, changes to one will affect the other and vice versa −

example: changes to d2 will change d1, changes to d1 will change d2



only valid if both properties are both binding properties and observable properties, then you can bind them with the bindBidirectional method

Common Properties and Methods for Nodes

Common Properties and Methods for Nodes ❂

The Node class defines many properties and methods that are common to all nodes.



Most JavaFX style properties are similar to CSS (yea from CS-120) −

JavaFX calls these JavaFX CSS



More about properties : ✦



https://docs.oracle.com/javafx/2/api/javafx/scene/docfiles/cssref.html

The syntax for a style is always: styleName:value −

multiple properties for a node can be listed separated by a semicolon.

Common Properties and Methods for Nodes ❂

Example: You can set two properties of a circle using the following: circle.setStyle("-fx-stroke: black; -fx-fill: red;"); −

sets the outline of the circle to be black



sets the color inside the circle to be red



this line is equivalent to: circle.setStroke(Color.BLACK); circle.setFill(Color.RED);



If you use the incorrect JavaFX CSS your program will still work, but the style will be ignored.

Common Properties and Methods for Nodes ❂



The rotate property lets you specify the angle (in degrees) for rotating a node from its center. −

positive degrees rotate clockwise



negative degrees rotate counterclockwise

Example: The following rotates a button 80 degrees button.setRotate(80)

Common Properties and Methods for Nodes ❂

See NodeStyleRotateDemo.java

The Color Class

The Color Class ❂

used to create colors



The abstract Paint class is used for painting a Node



javafx.scene.paint.Color is a concrete subclass of paint used to encapsulate colors

The Color Class

The Color Class ❂

Creating a color: public Color(double r, double g, double b, double opacity);





r, g, b are the red, green, blue components of a color, value range from 0.0 (darkest) to 1.0 (lightest shade)



opacity is the color transparency between 0.0 (completely transparent) to 1.0 (completely opaque)



This follows the RGBA (red, green, blue, alpha) color model.

Example: Color color = new Color(0.25, 0.14, 0.333, 0.51);

The Color Class ❂

Color is immutable −

any methods which "alter" the color actually create a new object and return that object.



You can also create a color using some of the static methods of the Color class.



You can also use some of the standard colors which are defined as constants in the Color class. −

See the API for Color



Example: circle.setFill(Color.RED);

The Font Class

The Font Class ❂

used to create and set fonts and change their properties.



Font has a name, weight, posture, and size.



You can see a list of available font family names by calling getFamilies().



FontPosture is for italics or no italics: −

FontPosture.ITALIC



FontPosture.REGULAR

The Font Class

The Font Class ❂

See: FontDemo.java

The Image and ImageView Classes

The Image and ImageView Classes ❂



javafx.scene.image.Image represents an image specified by a URL or filename. −

new Image("image/us.gif")



new Image("http://somewebsite.com/us.gif")

javafx.scene.image.ImageView is a node for displaying an image and can be created from an Image object Image image = new Image("image/us.gif"); ImageView imageView = new ImageView(image);



You can also make an ImageView directly from a file or URL: ImageView imageView = new ImageView("image/us.gif");

The Image and ImageView Classes

The Image and ImageView Classes ❂

See Code: ShowImage.java



NOTE: The image file must be in the same directory as the class file. −

For Eclipse make sure the images are in the project folder.

Shapes

Shapes ❂

JavaFX provides many ways to draw text, lines, circles, rectangles, ellipses, arcs, polygons, and polylines.



Shape is an abstract base class that defines the common properties of all shapes.

Shapes - Text ❂

Text class defines a node that displays a string at a starting point (x, y)



Usually placed in a pane. −

upper-left corner of a pane is (0, 0)



bottom-right point is ( pane.getWidth(), pane.getHeight() )



Use \n to break a string over multiple lines.



See Code: ShowText.java

Shapes - Text

Shapes - Text

Shapes - Line ❂

A line connects two points with four parameters startX, startY, endX, and endY



See Code: ShowLine.java

Shapes - Line

Shapes - Rectangle ❂

defined by parameters x, y, width, height, arcWidth, and arcHeight



upper-left corner is point at (x, y) and parameter aw (arcWidth) the horizontal diameter of the arcs at the corner, and ah (arcHeight) the vertical diameter of the arcs at the corner



See Code: ShowRectangle.java

Shapes - Rectangle

Shapes - Rectangle

Shapes – Circle and Ellipse ❂

Circles are defined by centerX, centerY, and radius



An Ellipse is defined by centerX, centerY, radiusX, and radiusY



See Code: ShowEllipse.java and ShowCircle.java

Shapes – Circle and Ellipse

Shapes – Circle and Ellipse

Shapes – Arc ❂

Part of an ellipse



defined by centerX, centerY, radiusX, radiusY, startAngle, length, and an arc type (ArcType.OPEN, ArchType.CHORD, or ArcType.ROUND)



Angles are measured in degrees and follow the normal math conventions (0 is in the easterly direction, positive angles go counterclockwise from the easterly direction)



See Code: ShowArc.java

Shapes – Arc

Shapes – Arc

Shapes – Arc

Shapes – Polygon and Polyline ❂

Polygon defines a polygon that connects a sequence of points.



Polyline is similar to Polygon but the class is not automatically closed.



See Code: ShowPolygon.java

Shapes – Polygon and Polyline

Case Study: The ClockPane Class

Case Study: The ClockPane Class ❂

Example of a class which displays a clock on a pane.

Case Study: The ClockPane Class

Suggest Documents