You are on page 1of 71

JavaFX GUI Basics

Disclaimer and Acknowledgement


Some slides of this presentation are created from Building GUI Applications With JavaFX tutorial
> http !!"ava#sun#com!"avaf$!%!tutorials!ui!

Topics
&uic' JavaFX GUI (vervie) Using *eclarative s+nta$ for creating GUI Step ,+ step process for creating a simple GUI JavaFX Application structure - Stage. Scene Scene Graph /ustom node Graphical o,"ects 0ffects Interactions
3

Quick JavaFX GUI Overview

User Inter ace !lements


Standard UI components +ou can create using the javafx.ext.swing pac'age#

"olors
/olor patterns for all constants of the javafx.scene.paint.Color class

#$apes and Fill #t%les


javafx.scene.shape and javafx.scene.paint pac'ages

Te&t
*ifferent formatting st+les applied to the same te$t string

! ects
0ffects can ,e applied to the JavaFX UI elements

Trans ormation
1ransformations can ,e performed for the graphics. images. or te$t

10

'a%out
1here are several methods of la+ing out UI elements using the javafx.scene.layout pac'age#

11

"ursors
*ifferent vie)s of cursor +ou can appl+ to an+ UI element

12

Using Declarative #%nta& ( or "reating GUI)

*$% Declarative #%nta& or Building GUI+


Because the structure of declared o,"ects in the code reflects the visual structure of the scene graph. and this ena,les +ou to understand and maintain the code easil+# 1he order of elements +ou declare in the code matches the order in )hich the+ appear in the application#

14

#tep ,% #tep -rocess o "reating a #imple GUI

#tep ,% #tep -rocess o "reating a simple GUI


JavaFX application that renders a green rounded rectangle and a )hite circle )ith red outline on the top of the rectangle

16

#tep ,% #tep -rocess o "reating a GUI


%#Add necessar+ imports 2#/reate an Application )indo) 3#Set the Scene 4#/reate a 5ectangle 6#/reate a /ircle 7#/hange the code 8so that the /ircle gets underneath the 5ectangle9
17

./ Add 0ecessar% 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

1/ "reate an Application *indow


In order to displa+ the graphics. +ou need to create a )indo) through Stage o,"ect literal
// Create a Stage o ject literal. Stage is required to render any o ject. // !he window should e ig enough to display all of the rectangle and // the circle. "n this example# the window is a rectangle of $%& y $'( // pixels. !o create a window of this si)e# with a *+eclaring is ,asy* title# // declare these values within the curly rackets using the following codeStage . title- *+eclaring "s ,asy/* width- $%& height- $'( visi le- true 0

19

2/ #et t$e #cene


Within the stage. set the scene to hold 1ode o,"ects such as a circle or a rectangle 1he scene is a root area )here +ou place o,"ects of the node t+pe# 1he scene has content varia,le that is used to hold the nodes# 1here are man+ different 'inds of nodes. such as graphical o,"ects. te$t. and GUI components#
20

2/ #et t$e #cene ("ontinued)


// !he content of the window ecomes filled with white ecause // white is a default fill color for a scene. !he scene is placed on top // of the window. Stage . ... scene- Scene . content- 2 3 0 0

21

3/ "reate a 4ectangle
Stage . ... scene- Scene . content- 2 // !he x and y instance varia les specify the pixel location of the // rectangle# arc4idth and arc5eight define the roundness of // corners# and the fill varia le defines the color that fills the rectangle. Rectangle . x- %' y- 6' width- ('7 height- ('7 arc4idth- (' arc5eight- (' fill- Color.8R,,1 0 3 0 22

5/ "reate a "ircle
Stage { ... scene: Scene { content: [ Rectangle { ... }, // Because the rectangle is declared before any other objects, it is painted // first. The rectangle ill be behind any other objects painted later. !ircle{ center": ##$ center%: ##& radius: $' fill: !olor.()*T+ stro,e: !olor.R+} . }

23

6/ -lace "ircle Underneat$ 4ectangle


Stage { ... scene: Scene { content: [ // /lace the circle underneath the s0uare. To do so, s itch the order // of the circle and s0uare !ircle{ .... }, Rectangle { ... } . } }
24

JavaFX Application #tructure

#tage
1op-level container for a scene
> /ontains onl+ one Scene

:otentiall+ represented ,+
> JFrame on des'top > JApplet on )e, page > S;G pla+er on mo,ile

*efines the characteristics li'e title. )idth. height. location. handling e$it. etc

26

!&ample7 #tage
Stage . title- *4elcome to 9ava:;/* scene- Scene . content- 2 !ext . content- *5ello 4orld/* x-$' y-$' fill- Color.<=>C? font- :ont. si)e- 6$ 0 0 3 0 0

27

JavaFX Application !&ecution 8odel


Stage or Stage varia,les
> Stage o,"ect > Stage varia,les < cannot create Stage o,"ects in file )ith

class definition

run@A function
> Will ,e e$ecuted as thread
Main.fx
Scene { ... } function run(): Void { ...
Displayed

Executed as a thread 28

#cene
/anvas upon )hich Scene Graph is displa+ed /an set multiple /SS st+lesheets /an set ,ac'ground color 8or set to null9 /an set canvas )idth!height

29

#cene Grap$

*$at is #cene Grap$+


1he scene graph is a tree-li'e data structure )hich defines a hierarch+ of graphical o,"ects in a scene# A single element in the scene graph is called a node#
> 0ach node has one parent e$cept for the root node. )hich

has no parent# > 0ach node is either a leaf node or a ,ranch# > A leaf node has no children# > A ,ranch node has =ero or more children#

31

JavaFX Arc$itecture
Java&' $cript $" tware
!r"#ect $ce%e Graph E ects Java 2D

("dels a G)* part " a Java&' applicati"%

Graphics hardware

32

Basic Grap$ical O,9ects


Graphical o,"ects as e$amples of >odes
> 1e$t. geometric shapes. te$t. S)ing components

Some common attri,utes in nodes


> 1ransformation < translate. shear. rotate. scale > /lip < displa+ing onl+ part of the node ,ased on a geometric

shape > 0ffect < t+pe of effect. eg# ,lurring. shado)ing. to appl+ > 0vents < mouse. 'e+,oard > (pacit+ < setting the translucenc+
33

*$at is #cene Grap$+


A hierarchical representation of graphical o,"ects
> 1ree li'e structure > Basis of JavaFX graphics engine

Scene graph elements


> >odes < images. te$t. S)ing )idgets > State < visi,ilit+. opacit+. transformation > 0vents < mouse. 'e+,oard. node updates > Animation < var+ing properties over time

A scene graph 'no)s ho) to render itself??


> JavaFX scene graph engine is availa,le at

http !!scenegraph#dev#"ava#net > Usa,le from Java

34

#cene Grap$7 Group


Group stands a set of >odes )hich ma+ have same effect Group itself is a >ode. so can ,e nested

35

#cene Grap$7 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

"ustom 0ode

"ustom 0ode
:rimar+ means of Scene Graph encapsulation
> All other nodes are not e$tenda,le

Simpl+ override the create@A method. )hich returns a >ode o,"ect

38

#$apes

#$apes
Arc /ircle 0llipse @ine :ath :ol+gon 5ectangle stro'e stro'eWidth fill smooth

40

Geometric #$apes
Arc. ellipse. line. pol+gon. circle. rectangle ;er+ similar to te$t
Circle { centerX: 70, centerY: 70 radius: 50 fill: Color.PINK stroke: Color.RED strokeWidth: 3 strokeDashArray: [ 7 ] strokeDashOffset: 2 }

41

"ustom #$apes
1)o )a+s of defining custom shapes
> /om,ining e$isting shapes > *ra)ing a totall+ ne) shape

/om,ine e$isting shape )ith ShapeIntersect or ShapeSubtract


> 0ither add or su,tract from shape

*ra) ne) shapes )ith Path and path elements


> :ath elements include Aove1o. Arc1o. B@ine. ;@ine. &uad/urve.

etc#

/an ,e manipulated li'e a regular geometric shape


42

!&ample : #$apeIntersect
ShapeIntersect { transforms: [ Translate { x: 170 } ] fill: Color.LIGHTGREEN stroke: Color.GREEN strokeWidth: 3 //Union of the 2 shapes a: [rectangle diamond ] }

43

!&ample : -at$
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

Ot$er Grap$ical O,9ects

Te&t
$. +. 1e$t(rigin B+ default. te$t positioned such that 8$. +9 is left ,aseline Fonts can ,e specified on 1e$t Favor fill over stro'e Supports multiple te$t Use Alignment to align multi-line te$t 1o center te$t. compute the center via la+out ,ounds
46

Te&t
*efines a node for displa+ing te$t
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
"mageBiew node sho)s images Image represents an in-memor+ image Image can load images in foreground thread or ,ac'ground thread Both Image;ie) and Image can scale
> :reserve ratio > Fit )ithin a specific )idth!height > When fit on Image level. 'eeps smaller image in memor+

48

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

49

Te&tBo&
Used for te$t input Use /SS to st+le the 1e$tBo$ te$t is changed to reflect the actual te$t in the 1e$tBo$ value is changed )hen the te$t is committed via 0>105. 1AB. etc action function is invo'ed )hen 0>105 is pressed columns specifies the preferred )idth ,ased on the font si=e and num,er of characters to displa+
50

! ects

;ow ! ect *orks


javafx.scene.effect pac'age A:I# All of the core filter effect classes e$tend the a,stract javafx.scene.effect.,ffect ,ase class# An+ 0ffect instance can ,e applied to a scene graph >ode ,+ setting the 1ode.effect varia,le# 0ach 0ffect su,class e$poses a small num,er of varia,les that control the visual appearance of the >ode# In addition. most 0ffect su,classes provide one or more input varia,les that can ,e used to CchainC effects
52

<aria,les In a ! ect "lass


0ach varia,le is generall+ documented )ith default. minimum. ma$imum. and identit+ values. )hich ma'es it eas+ to see the accepta,le range of values# *eveloper onl+ need to concern +ourself )ith turning the values of these varia,les# 1he effects frame)or' does all the heav+ lifting for +ou. such as painting the >ode into an offscreen image at the appropriate resolution. manipulating the pi$els in one of the /:U and!or G:U accelerated ,ac'ends. and automaticall+ repainting the affected portion of the scene#

53

! ects7 Drop#$adow

!&ample7 Drop#$adow class


+ropShadow class provides 6 varia,les
> color 1he shado) /olor > > > >

> default /olor#B@A/D offsetX 1he shado) offset in the $ direction. in pi$els# > default E#E offsetF 1he shado) offset in the + direction. in pi$els# > default E#E radius 1he radius of the shado) ,lur 'ernel# > default %E#E. ma$ 73#E spread 1he spread of the shado)# > default E#E. ma$ %#E. min E#E
55

!&ample7 Drop#$adow
!ext . effect- +ropShadow . offsetC- 6 color- Color.color@7.%# 7.%# 7.%A 0; ... 0# Circle . effect- +ropShadow . offsetC- % 0# ... 0
56

!&ample7 Drop#$adow
!ext . effect- +ropShadow . offsetC- 6 color- Color.8R,,1 radius- $7.7 0; ... 0# Circle . effect- +ropShadow . offset;- (7 offsetC- $7 color- Color.<=D, radius- 67.7 0

57

!&ample7 Drop#$adow "lass


Appl+ a *ropShado) effect to a rounded 5ectangle and control its appearance through the magic of the ,ind operator#
Rectangle . effect- +ropShadow . radius- ind radius 0 x- '7 y- 67 width- ('7 height- (77 arc4idth- %7 arc5eight- %7 fill- Color.R,+ 0
58

! ects7 'ig$ting

'ig$ting ! ect
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

! ects7 -erspectiveTrans orm

-erspectiveTrans orm "lass


Used to provide a Cfau$C three-dimensional effect for other)ise t)o-dimensional content#
Group { effect: PerspectiveTransform { ulx: 10 uly: 10 urx: 310 ury: 40 lrx: 310 lry: 60 llx: 10 lly: 90 } cache: true content: !ectan"le { x: 10 y: 10 #i$th: %&0 hei"ht: &0 fill: 'olor()*+, }Text { x: %0 y: 6. content: /Perspective/ fill: 'olor(0,**12 font: 3ont(font4null- 3ont2ei"ht()1*5- 3667 }8

62

! ects7 'inear Gradients

'inear Gradients
startX. startF. endX. endF
> *efine the direction of the gradient > (n the unit sGuare

Stops define each step in the gradient# 0ach stop


> Bas an offset ,et)een E###% > Bas a color

64

! ects7 Glow= 4e lection= GaussianBlur

#ome ! ects #upported In JavaFX


effect: SepiaTone { level: 0.5 }

effect: Glow { level: 0.7 }

+ri,i%al i-a,e

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

effect: Reflection { fraction: 0.7 }

66

Interactions

;andling !vents
All nodes have either mouse or 'e+,oard events
> (verride the appropriate method

Aouse events < onAouseXXXX89


> XXXX H 0ntered. 0$ited. :ressed. *ragged. Aoved. /lic'ed.

5eleased. WheelAoved

De+,oard events < onDe+,oardXXXX89


> XXXX H :ressed. 5eleased. 1+ped

Indicate interactivit+ ,+ changing cursor


> Set the cursor attri,ute
68

!&ample7 ;andling !vents


Aouse 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


*rag an o,"ect 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

You might also like