JavaFX Basics rights reserved. 1 Motivations JavaFX is a new framework for developing Java GUI programs. The JavaFX API is an excellent example of how the object-oriented principle is applied. This chapter serves two purposes. First, it presents the basics of JavaFX programming. Second, it uses JavaFX to demonstrate OOP. Specifically, this chapter introduces the framework of JavaFX and discusses JavaFX GUI components and their relationships. rights reserved. 2
JavaFX vs Swing and AWT Swing and AWT are replaced by the JavaFX platform for developing rich Internet applications. When Java was introduced, the GUI classes were bundled in a library known as the Abstract Windows Toolkit (AWT). AWT is fine for developing simple graphical user interfaces, but not for developing comprehensive GUI projects. In addition, AWT is prone to platform-specific bugs. The AWT user-interface components were replaced by a more robust, versatile, and flexible library known as Swing components. Swing components are painted directly on canvases using Java code. Swing componentsdependlessonthetargetplatformanduselessofthe native GUI resource. With the release of Java 8, Swing is replaced by a completely new GUI platform known as JavaFX. rights reserved. 3 Installing JavaFX& Scene Builder e(fx)clipse is an extension for your Eclipse IDE Extensions like this can be installed using the "Install New Software" wizard. Eclipsedoesnotknowaboutthelocationofthee(fx)clipsesoyou needtoaddtherepositoryasasoftwaresite. Theaddress is: http://download.eclipse.org/efxclipse/updates-released/1.2.0/site rights reserved. 4
Installing JavaFX& Scene Builder In the tree of installable features, check only the entry corresponding to your release: e(fx)clipse- IDE Also, make sure the "Contact all update sites during install to find required software" is checked. You may, however, install the FX time feature into your IDE but we strongly recommend composing your own target platform. When requested, restart Eclipse. rights reserved. 5 Installing JavaFX& Scene Builder The JavaFX Scene Builder is available as a Windows package (.msi) for the Windows platform, as a Debian package(.deb) or.tar.gzfileforthelinuxplatform,andasadiskimage(.dmg)for themacosxplatform. Download JavaFX Scene Builder from the Additional Resources section of the Java SE Downloads page at http://www.oracle.com/technetwork/java/javase/downloads/index.html By default, the JavaFX Scene Builder software is installed at C:\Program Files\Oracle\JavaFX Scene Builder 2.0 on a Windows platform. If you install JavaFX Scene Builder on a 64-bit Windows machine, the default installation location is C:\Program Files(x86)\Oracle\JavaFX Scene Builder 2.0. rights reserved. 6
Installing JavaFX& Scene Builder rights reserved. 7 Eclipse Configurations WeneedtotellEclipsetouseJDK8andalsowhereitwillfind the Scene Builder: 1. Open the Eclipse Preferences and navigate to Java Installed JREs. 2. Click Add..., select Standard VM and choose the installation Directory of yourjdk8. 3. RemovetheotherJREsorJDKssothattheJDK8becomesthedefault. rights reserved. 8
Eclipse Configurations 4. Navigate to Java Compiler. Set the Compiler compliance level to 1.8. rights reserved. 9 Eclipse Configurations 5. Navigate to the JavaFX preferences. Specify the path to your Scene Builder executable. rights reserved. 10
Basic Structure of JavaFX Application Override the start(stage) method Stage, Scene, and Nodes Stage Scene Button MyJavaFX MultipleStageDemo rights reserved. 11 Basic Structure of JavaFX It'slikeatheaterplay:TheStageisthemaincontainerwhichis usually a Window with a border and the typical minimize, maximize and close buttons. Inside the Stage you add a Scene whichcan,ofcourse,beswitchedoutbyanotherscene.insidethe Scene the actual JavaFX nodes like AnchorPane, TextBox, etc. are added. rights reserved. 12
Example JavaFX Types Classes o JavaFX Main Class Extends JavaFX Application Contains main() and launch() launch() will initialise and call start() which must be defined o FXML XML based language Describes UI appearance Controlled by Scene Builder UI Layouts o Rootpane Base forui scene Can havea menubar o AnchorPane Used to anchor components o SplitPane o TableView o GridPane o TilePane o Hbox Setsboxwrappertocontain horizontal components rights reserved. 13 JavaFX Classes o Stage Represents the main container and window o Scene Adds features to Stage, representing FXML layouts o FXMLLoader Handles parsing of FXML files into Java Class @FXML keyword links private Java variables to corresponding FXML components @FXML private TableView<person> persontable; o JavaFX Collections Data Structures that have Event Listeners Can handle changes made in GUI automatically ObservableList is example of array with Listener rights reserved. 14
What is FXML? FXML is an XML-based language that provides the structure for building a user interface separate from the application logic of your code. This separation of the presentation and application logic is attractive to web developers because they can assemble a user interface that leverages Java components without mastering thecodeforfetchingandfillinginthedata. FXML does not have a schema, but it does have a basic predefined structure. What you can express in FXML, and how itappliestoconstructingascenegraph,dependsontheapiof the objects you are constructing. Because FXML maps directly to Java, you can use the API documentation to understand what elements and attributes are allowed. In general, most JavaFX classes can be used as elements, and most Bean properties can be used as attributes. rights reserved. 15 FXML and Scene Builder Just as some developers prefer to work directly in the XML code, other developersprefertouseatooltoauthortheirxml.thesameistrue with FXML. Ifyouprefertouseatool,orifyouwanttocreateaquickprototypetoget feedback, then you might prefer to use JavaFX Scene Builder. SceneBuilderisadesigntoolthatgeneratestheFXMLsourcecodeasyou define the user interface for your application. Scene Builder can help you to quickly create a prototype for an interactive application that connects components to the application logic. Because Scene Builder uses XML as a serialization format, the produced FXMLcodeisveryclearandyoucanfurthereditFXMLfiles,generatedby SceneBuilder,inanytextorXMLeditor. rights reserved. 16
Scene Builder rights reserved. 17 FXML UI Components rights reserved. 18
CSS Styling CanstyleFXMLfeatureswithCSS Edit appearance using controls for colour, background, text and sizing SimilartousingCSSwithHTML rights reserved. 19 Advanced JavaFX Components o FileChooser Opens Directory Browser o TreeView Creates hierarchical list views for nest features o HTMLEditor Advanced text editor with HTML features o WebViewer Inbuilt web display Handles HTML5, CSS, JavaScript, DOM, SVG rights reserved. 20
Panes, UI Controls, and Shapes ButtonInPane rights reserved. 21 Display a Shape This example displays a circle in the center of the pane. (0, 0) X Axis Y Axis y Y Axis (x, y) Java Coordinate System Conventional Coordinate System (0, 0) X Axis ShowCircle rights reserved. 22
Binding Properties JavaFX introduces a new concept called binding property that enables a target objectto 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 objector a binding property. ShowCircleCentered rights reserved. 23 Binding Property: getter, setter, and property getter rights reserved. 24
Common Properties and Methods for Nodes style: set a JavaFX CSS style rotate: Rotate a node NodeStyleRotateDemo rights reserved. 25 The Color Class rights reserved. 26
The Font Class FontDemo rights reserved. 27 The Image Class rights reserved. 28
The ImageView Class ShowImage rights reserved. 29 Layout Panes JavaFX provides many types of panes for organizing nodes in a container. rights reserved. 30
FlowPane ShowFlowPane rights reserved. 31 GridPane ShowGridPane rights reserved. 32
BorderPane ShowBorderPane rights reserved. 33 HBox rights reserved. 34
VBox ShowHBoxVBox rights reserved. 35 Shapes JavaFX provides many shape classes for drawing texts, lines, circles, rectangles, ellipses, arcs, polygons, and polylines. rights reserved. 36
Text rights reserved. 37 Text Example ShowText rights reserved. 38
Line ShowLine rights reserved. 39 Rectangle rights reserved. 40
Rectangle Example ShowRectangle rights reserved. 41 Circle rights reserved. 42
Ellipse radiusx radiusy (centerx, centery) ShowEllipse rights reserved. 43 Arc rights reserved. 44
Arc Examples radiusy length startangle 0 degree radiusx (centerx, centery) 30 20 50 20 (a) Negative starting angle 30 and negative spanning angle 20 (b) Negative starting angle 50 and positive spanning angle 20 ShowArc rights reserved. 45 Polygon and Polyline ShowArc rights reserved. 46
Polygon +Polygon() javafx.scene.shape.polygon +Polygon(double... points) +getpoints(): ObservableList<Double> The getter and setter methods for property values and a getter for property itself are provided in the class, but omitted in the UML diagram for brevity. Creates an empty polygon. Creates a polygon with the given points. Returns a list of double values as x- and y-coordinates of the points. ShowPolygon rights reserved. 47 Case Study: The ClockPane Class This case study develops a class that displays a clock on a pane. javafx.scene.layout.panel -hour: int -minute: int -second: int ClockPane +ClockPane() +ClockPane(hour: int, minute: int, second: int) +setcurrenttime(): void +setwidth(width: double): void +setheighttime(height: double): void The getter and setter methods for these data fields are provided in the class, but omitted in the UML diagram for brevity. The hour in the clock. The minute in the clock. The second in the clock. Constructs a default clock for the current time. Constructs a clock with the specified time. Sets hour, minute, and second for current time. Sets clock pane s width and repaint the clock, Sets clock pane s height and repaint the clock, ClockPane rights reserved. 48
Use the ClockPane Class DisplayClock rights reserved. 49