Você está na página 1de 71

JavaFX GUI Basics

Disclaimer and Acknowledgement


Some slides of this presentation are created from Building GUI Applications With JavaFX tutorial
> http://java.sun.com/javafx/1/tutorials/ui/

Topics
Quick JavaFX GUI Overview Using Declarative syntax for creating GUI Step by step process for creating a simple GUI JavaFX Application structure - Stage, Scene Scene Graph Custom node Graphical objects Effects Interactions
3

Quick JavaFX GUI Overview

User Interface Elements


Standard UI components you can create using the javafx.ext.swing package.

Colors
Color patterns for all constants of the javafx.scene.paint.Color class

Shapes and Fill Styles


javafx.scene.shape and javafx.scene.paint packages

Text
Different formatting styles applied to the same text string

Effects
Effects can be applied to the JavaFX UI elements

Transformation
Transformations can be performed for the graphics, images, or text

10

Layout
There are several methods of laying out UI elements using the javafx.scene.layout package.

11

Cursors
Different views of cursor you can apply to any UI element

12

Using Declarative Syntax (for Creating GUI)

Why Declarative Syntax for Building GUI?


Because the structure of declared objects in the code reflects the visual structure of the scene graph, and this enables you to understand and maintain the code easily. The order of elements you declare in the code matches the order in which they appear in the application.

14

Step by Step Process of Creating a Simple GUI

Step by Step Process of Creating a simple GUI


JavaFX application that renders a green rounded rectangle and a white circle with red outline on the top of the rectangle

16

Step by Step Process of Creating a GUI


1.Add necessary imports 2.Create an Application window 3.Set the Scene 4.Create a Rectangle 5.Create a Circle 6.Change the code (so that the Circle gets underneath the Rectangle)
17

1. Add Necessary Imports


import javafx.stage.Stage; import javafx.scene.Scene; // required to render a window // required to display a circle and // rectangle on a window import javafx.scene.shape.Rectangle; // required to render the rectangle import javafx.scene.paint.Color; import javafx.scene.shape.Circle; // required to fill and stroke the // rectangle and circle with color // required to render the circle

18

2. Create an Application Window


In order to display the graphics, you need to create a window through Stage object literal
// Create a Stage object literal. Stage is required to render any object. // The window should be big enough to display all of the rectangle and // the circle. In this example, the window is a rectangle of 249 by 251 // pixels. To create a window of this size, with a "Declaring is Easy" title, // declare these values within the curly brackets using the following code: Stage { title: "Declaring Is Easy!" width: 249 height: 251 visible: true }

19

3. Set the Scene


Within the stage, set the scene to hold Node objects such as a circle or a rectangle The scene is a root area where you place objects of the node type. The scene has content variable that is used to hold the nodes. There are many different kinds of nodes, such as graphical objects, text, and GUI components.
20

3. Set the Scene (Continued)


// The content of the window becomes filled with white because // white is a default fill color for a scene. The scene is placed on top // of the window. Stage { ... scene: Scene { content: [ ] } }

21

4. Create a Rectangle
Stage { ... scene: Scene { content: [ // The x and y instance variables specify the pixel location of the // rectangle, arcWidth and arcHeight define the roundness of // corners, and the fill variable defines the color that fills the rectangle. Rectangle { x: 45 y: 35 width: 150 height: 150 arcWidth: 15 arcHeight: 15 fill: Color.GREEN } ] } 22

5. Create a Circle
Stage { ... scene: Scene { content: [ Rectangle { ... }, // Because the rectangle is declared before any other objects, it is painted // first. The rectangle will be behind any other objects painted later. Circle{ centerX: 118 centerY: 110 radius: 83 fill: Color.WHITE stroke: Color.RED } ] }

23

6. Place Circle Underneath Rectangle


Stage { ... scene: Scene { content: [ // Place the circle underneath the square. To do so, switch the order // of the circle and square Circle{ .... }, Rectangle { ... } ] } }
24

JavaFX Application Structure

Stage
Top-level container for a scene
> Contains only one Scene

Potentially represented by
> JFrame on desktop > JApplet on web page > SVG player on mobile

Defines the characteristics like title, width, height, location, handling exit, etc

26

Example: Stage
Stage { title: "Welcome to JavaFX!" scene: Scene { content: [ Text { content: "Hello World!" x:25 y:25 fill: Color.BLACK font: Font{ size: 32 } } ] } }

27

JavaFX Application Execution Model


Stage or Stage variables
> Stage object > Stage variables cannot create Stage objects in file with

class definition

run() function
> Will be executed as thread
Main.fx
Scene { ... } function run(): Void { ...
Displayed

Executed as a thread 28

Scene
Canvas upon which Scene Graph is displayed Can set multiple CSS stylesheets Can set background color (or set to null) Can set canvas width/height

29

Scene Graph

What is Scene Graph?


The scene graph is a tree-like data structure which defines a hierarchy of graphical objects in a scene. A single element in the scene graph is called a node.
> Each node has one parent except for the root node, which

has no parent. > Each node is either a leaf node or a branch. > A leaf node has no children. > A branch node has zero or more children.

31

JavaFX Architecture
JavaFX Script Software
Project Scene Graph Effects Java 2D

Models a GUI part of a JavaFX application

Graphics hardware

32

Basic Graphical Objects


Graphical objects as examples of Nodes
> Text, geometric shapes, text, Swing components

Some common attributes in nodes


> Transformation translate, shear, rotate, scale > Clip displaying only part of the node based on a geometric

shape > Effect type of effect, eg. blurring, shadowing, to apply > Events mouse, keyboard > Opacity setting the translucency
33

What is Scene Graph?


A hierarchical representation of graphical objects
> Tree like structure > Basis of JavaFX graphics engine

Scene graph elements


> Nodes images, text, Swing widgets > State visibility, opacity, transformation > Events mouse, keyboard, node updates > Animation varying properties over time

A scene graph knows how to render itself!!


> JavaFX scene graph engine is available at

http://scenegraph.dev.java.net > Usable from Java

34

Scene Graph: Group


Group stands a set of Nodes which may have same effect Group itself is a Node, so can be nested

35

Scene Graph: Group


Group { transforms: Translate { x:15, y, 15 } content: [ Text { x: 10, y: 50 font: Font: { size: 50 } content: Hello World } Circle { centerX: 100, centerY: 100 radius: 40 fill: Color.BLACK } ] }
Gro up

x : 1 5 y: 1 5

Text

Circle

36

Custom Node

Custom Node
Primary means of Scene Graph encapsulation
> All other nodes are not extendable

Simply override the create() method, which returns a Node object

38

Shapes

Shapes
Arc Circle Ellipse Line Path Polygon Rectangle stroke strokeWidth fill smooth

40

Geometric Shapes
Arc, ellipse, line, polygon, circle, rectangle Very similar to text
Circle { centerX: 70, centerY: 70 radius: 50 fill: Color.PINK stroke: Color.RED strokeWidth: 3 strokeDashArray: [ 7 ] strokeDashOffset: 2 }

41

Custom Shapes
Two ways of defining custom shapes
> Combining existing shapes > Drawing a totally new shape

Combine existing shape with ShapeIntersect or ShapeSubtract


> Either add or subtract from shape

Draw new shapes with Path and path elements


> Path elements include MoveTo, ArcTo, HLine, VLine, QuadCurve,

etc.

Can be manipulated like a regular geometric shape


42

Example ShapeIntersect
ShapeIntersect { transforms: [ Translate { x: 170 } ] fill: Color.LIGHTGREEN stroke: Color.GREEN strokeWidth: 3 //Union of the 2 shapes a: [rectangle diamond ] }

43

Example Path
Path { fill: Color.LIGHTGRAY stroke: Color.GRAY strokeWidth: 3 elements: [ MoveTo { x: 15 y: 15 }, ArcTo { x: 50 y: 10 radiusX: 20 radiusY: 20 sweepFlag: true}, ArcTo { x: 70 y: 20 radiusX: 20 radiusY: 20 sweepFlag: true}, ArcTo { x: 50 y: 60 radiusX: 20 radiusY: 20 sweepFlag: true}, ArcTo { x: 20 y: 50 radiusX: 10 radiusY: 5 sweepFlag: false}, ArcTo { x: 15 y: 15 radiusX: 10 radiusY: 10 sweepFlag: true}, ] }
44

Other Graphical Objects

Text
x, y, TextOrigin By default, text positioned such that (x, y) is left baseline Fonts can be specified on Text Favor fill over stroke Supports multiple text Use Alignment to align multi-line text To center text, compute the center via layout bounds
46

Text
Defines a node for displaying text
Text { effect: DropShadow { offsetX: -10 offsetY: -10 } font: Font { name: DirtyBakersDozen size: 50 } fill: Color.ROYALBLUE stroke: Color.BLUE, strokeWidth: 3 x: 15, y: 80 content: "Hello World" }
47

Image
ImageView node shows images Image represents an in-memory image Image can load images in foreground thread or background thread Both ImageView and Image can scale
> Preserve ratio > Fit within a specific width/height > When fit on Image level, keeps smaller image in memory

48

Images
ImageView = ImageView { clip: Rectangle { y: 30 x: 50 width: 350 height: 100 } image: Image { url: "..."} }

49

TextBox
Used for text input Use CSS to style the TextBox text is changed to reflect the actual text in the TextBox value is changed when the text is committed via ENTER, TAB, etc action function is invoked when ENTER is pressed columns specifies the preferred width based on the font size and number of characters to display
50

Effects

How Effect Works


javafx.scene.effect package API. All of the core filter effect classes extend the abstract javafx.scene.effect.Effect base class. Any Effect instance can be applied to a scene graph Node by setting the Node.effect variable. Each Effect subclass exposes a small number of variables that control the visual appearance of the Node. In addition, most Effect subclasses provide one or more input variables that can be used to "chain" effects
52

Variables In a Effect Class


Each variable is generally documented with default, minimum, maximum, and identity values, which makes it easy to see the acceptable range of values. Developer only need to concern yourself with turning the values of these variables. The effects framework does all the heavy lifting for you, such as painting the Node into an offscreen image at the appropriate resolution, manipulating the pixels in one of the CPU and/or GPU accelerated backends, and automatically repainting the affected portion of the scene.

53

Effects: DropShadow

Example: DropShadow class


DropShadow class provides 5 variables
> color: The shadow Color > > > >

> default: Color.BLACK offsetX: The shadow offset in the x direction, in pixels. > default: 0.0 offsetY: The shadow offset in the y direction, in pixels. > default: 0.0 radius: The radius of the shadow blur kernel. > default: 10.0, max: 63.0 spread: The spread of the shadow. > default: 0.0, max: 1.0, min: 0.0
55

Example: DropShadow
Text { effect: DropShadow { offsetY: 3 color: Color.color(0.4, 0.4, 0.4) }; ... }, Circle { effect: DropShadow { offsetY: 4 }, ... }
56

Example: DropShadow
Text { effect: DropShadow { offsetY: 3 color: Color.GREEN radius: 20.0 }; ... }, Circle { effect: DropShadow { offsetX: 10 offsetY: 20 color: Color.BLUE radius: 30.0 }

57

Example: DropShadow Class


Apply a DropShadow effect to a rounded Rectangle and control its appearance through the magic of the bind operator.
Rectangle { effect: DropShadow { radius: bind radius } x: 50 y: 30 width: 150 height: 100 arcWidth: 40 arcHeight: 40 fill: Color.RED }
58

Effects: Lighting

Lighting Effect
effect: Lighting{ surfaceScale: 7 light: DistantLight{ azimuth: 90 elevation: 30 } }
effect: Lighting{ surfaceScale: 7 light: SpotLight { x: 0 y :0 z: 50 pointsAtX: 10 pointsAtY: 10 pointsAtZ: 0 color: Color.YELLOW } }
60

Effects: PerspectiveTransform

PerspectiveTransform Class
Used to provide a "faux" three-dimensional effect for otherwise two-dimensional content.
Group { effect: PerspectiveTransform { ulx: 10 uly: 10 urx: 310 ury: 40 lrx: 310 lry: 60 llx: 10 lly: 90 } cache: true content: [ Rectangle { x: 10 y: 10 width: 280 height: 80 fill: Color.BLUE }, Text { x: 20 y: 65 content: "Perspective" fill: Color.YELLOW font: Font.font(null, FontWeight.BOLD, 36); }, ]

62

Effects: Linear Gradients

Linear Gradients
startX, startY, endX, endY
> Define the direction of the gradient > On the unit square

Stops define each step in the gradient. Each stop


> Has an offset between 0...1 > Has a color

64

Effects: Glow, Reflection, GaussianBlur

Some Effects Supported In JavaFX


effect: SepiaTone { level: 0.5 }

effect: Glow { level: 0.7 }

Original image

effect: GaussianBlur { input: SepiaTone { level: 0.5 } radius: 10.0 }

effect: Reflection { fraction: 0.7 }

66

Interactions

Handling Events
All nodes have either mouse or keyboard events
> Override the appropriate method

Mouse events onMouseXXXX()


> XXXX = Entered, Exited, Pressed, Dragged, Moved, Clicked,

Released, WheelMoved

Keyboard events onKeyboardXXXX()


> XXXX = Pressed, Released, Typed

Indicate interactivity by changing cursor


> Set the cursor attribute
68

Example: Handling Events


Mouse events change the color of an rectangle
var rectangle:Rectangle = Rectangle { x: 20, y: 10 width: 150, height: 70 arcWidth: 50, arcHeight: 50 fill: Color.LIGHTBLUE stroke: Color.ROYALBLUE strokeWidth: 3 onMouseEntered: function( e: MouseEvent ):Void { rectangle.fill = Color.WHITESMOKE; } onMouseExited: function( e: MouseEvent ):Void { rectangle.fill = Color.LIGHTBLUE; } }

69

Drag and Drop


Drag an object around the screen
var sx:Number = 0; var dx:Number = 0; var sy:Number = 0; var dy:Number = 0; var rectangle:Rectangle = Rectangle { x: bind dx y: bind dy width: 150 height: 70 arcWidth: 50, arcHeight: 50 fill: Color.LIGHTBLUE stroke: Color.ROYALBLUE strokeWidth: 3 cursor: Cursor.HAND onMousePressed: function( e: MouseEvent ):Void { sx = e.dragX - dx; sy = e.dragY - dy; } onMouseDragged: function( e: MouseEvent ):Void { dx = e.dragX - sx; dy = e.dragY - sy; } }

70

JavaFX GUI Basics

71

Você também pode gostar