Programming With JavaFX - PoliTO

2y ago
11 Views
2 Downloads
3.42 MB
84 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Eli Jorgenson
Transcription

Programming with JavaFXTecniche di Programmazione – A.A. 2014/2015

Summary1.2.3.4.5.6.7.8.9.10.2About and HistoryBasic conceptsMinimal JavaFX ApplicationApplication structureThe Scene GraphEventsModel-View-ControllerThe Controller in FXMLProperties and bindingsResourcesTecniche di programmazioneA.A. 2014/2015

About and HistoryIntroduction to JavaFX

GUI in JavaGraphic framework available in Java SwingExtremely powerful, many extensions availableComplex to master, requires low-level handlingHard to create visually pleasing applicationsAlternatives available Most notable: SWT (Eclipse)Still cumbersome to masterOn a different Universe, web-based user interfacesbecame nicer and faster to create 4Tecniche di programmazioneA.A. 2014/2015

JavaFX 1.0 – forget itJavaFX 1 and JavaFX 2 are completely differentVersion 1 relied on a “scripting language” to describescenes, with ‘hooks’ to activate Java codeJavaFX 1.x is now deprecated 5Tecniche di programmazioneA.A. 2014/2015

JavaFX 2.xRedesigned from scratchThe JavaFX 2.x framework is entirely written in JavaFor visual layout, an XML file may also be used (calledFXML)Graphic appearance borrows from web-standard CSSstyle sheetsUI programming is based on easy to handle events andbindings Oracle plans to deprecate Swing in favor of JavaFX 2Now called JavaFX 8 (after Java 8 – JDK 1.8) 6Tecniche di programmazioneA.A. 2014/2015

Getting and running JavaFXJavaFX is already included in Oracle JDK 7 and JDK8 Not in JDK 6.xNot in OpenJDK (beware, Linux users!)JDK 8 includes significant JavaFX improvements.Recommended: JavaFX Scene BuilderEclipse: e(fx)clipse plugin, available in the Eclipse MarketplaceDownload links are in the course webpage 7Tecniche di programmazioneA.A. 2014/2015

Basic conceptsIntroduction to JavaFX

Key concepts in JavaFXStage: where the application will be displayed (e.g., aWindows’ window)Scene: one container of Nodes that compose one “page”of your applicationNode: an element in the Scene, with a visual appearanceand an interactive behavior. Nodes may be hierarchicallynested My best friend is the JavaFX JavaDoc niche di programmazioneA.A. 2014/2015

Some ‘Leaf’ Nodes (Controls)10Tecniche di programmazioneA.A. 2014/2015

Some ‘Parent’ Nodes (Container ‘Panes’) BorderPane (5-areas)Hbox,Vbox (linear sequence)StackPane (overlay all children)GridPane (row x columns)FlowPane (flowing boxes, wrap around)TilePane (flowpane with equally sized boxes)AnchorPane (magnetically attach nodes at corners orsides)11Tecniche di programmazioneA.A. 2014/2015

Some Nodes (Charts)12Tecniche di programmazioneA.A. 2014/2015

ChoiceBoxColorPickerComboBoxBaseNodes eHBoxjavafx.scene.NodeFocus 13Tecniche di programmazioneA.A. 2014/2015

And more coming http://jfxtras.org/14Tecniche di programmazioneA.A. 2014/2015

And more coming http://fxexperience.com/controlsfx/15Tecniche di programmazioneA.A. 2014/2015

Empty JavaFX windowpublic class Main extends Application {@Overridepublic void start(Stage stage) {Group root new Group(); // the root is Group or PaneScene scene new Scene(root, 500, 500, Color.BLACK);stage.setTitle("JavaFX Demo");stage.setScene(scene);stage.show();}public static void main(String[] args) {launch(args);}}16Tecniche di programmazioneA.A. 2014/2015

Adding some shapepublic class Main extends Application {@Overridepublic void start(Stage stage) {Group root new Group();Scene scene new Scene(root, 500, 500, Color.BLACK);stage.setTitle("JavaFX Demo");Rectangle rect new age.show();}}17Tecniche di programmazioneA.A. 2014/2015

How to add scene content In Java code By creating and adding new Node subclasses By using node Builder classes Standard way, in Java (boring and error-prone)Programming pattern, later on In FXML 18By writing XML directlyBy using the Scene EditorAnd loading the FXML into the applicationTecniche di programmazioneA.A. 2014/2015

JavaFX Scene Builder 2.019Tecniche di programmazioneA.A. 2014/2015

FXML fragment. . . HBox id "HBox" alignment "CENTER" spacing "15.0"AnchorPane.rightAnchor "23.0" AnchorPane.topAnchor "22.0" children Button id "button1" fx:id "newIssue" onAction "#newIssueFired"text "New" / Button id "button2" fx:id "saveIssue" onAction "#saveIssueFired"text "Save" / Button id "button3" fx:id "deleteIssue" onAction "#deleteIssueFired"text "Delete" / /children /HBox ImageView id "IssueTrackingLite" layoutX "14.0" layoutY "20.0" image Image url "@IssueTrackingLite.png" preserveRatio "true" smooth "true" / /image /ImageView . . .20Tecniche di programmazioneA.A. 2014/2015

Building a scene from FXMLpublic void start(Stage stage) throws Exception {Parent root l"));stage.setTitle("Circle Demo");stage.setScene(new Scene(root, 500, 150));stage.show();}21Tecniche di programmazioneA.A. 2014/2015

Application structureIntroduction to JavaFX

Separation of concerns23Tecniche di programmazioneA.A. 2014/2015

Typical Class Diagram25Tecniche di programmazioneA.A. 2014/2015

General rules A JavaFX application extendsjavafx.application.ApplicationThe main() method should call Application.launch()The start() method is the main entry point for all JavaFXapplications Called with a Stage connected to the Operating System’swindowThe content of the scene is represented as a hierarchicalscene graph of nodes 26Stage is the top-level JavaFX containerScene is the container for all contentTecniche di programmazioneA.A. 2014/2015

Minimal examplepublic class HelloWorld extends Application {public static void main(String[] args) {launch(args);}@Overridepublic void start(Stage primaryStage) {primaryStage.setTitle("Hello World!");StackPane root new StackPane();Button btn new Button();btn.setText("Say 'Hello setScene(new Scene(root, 300, 250));primaryStage.show();}}27Tecniche di programmazioneA.A. 2014/2015

Stage vs. Scenejavafx.stage.Stage javafx.scene.SceneThe JavaFX Stage class is thetop level JavaFX container.The primary Stage isconstructed by the platform.Additional Stage objects maybe constructed by theapplication.A stage can optionally havean owner Window.28 The container for all contentin a scene graphThe application must specifythe root Node for the scenegraphRoot may be Group (clips),Region, Control (resizes)If no initial size is specified, itwill automatically compute itTecniche di programmazioneA.A. 2014/2015

Nodes The Scene is populated with a tree of Nodes Nodes have Properties Visual (size, position, z-order, color, .)Contents (text, value, data sets, .)Programming (event handlers, controller)Nodes generate Events Layout componentsUI ControlsChartsShapesUI eventsNodes can be styled with CSS29Tecniche di programmazioneA.A. 2014/2015

Events FX Event (javafx.event.Event): Event Source a NodeEvent TargetEvent TypeUsually generated after some user actionActionEvent, TreeModificationEvent, InputEvent, ListView.EditEvent, MediaErrorEvent, nEvent, TreeView.EditEvent, WebEvent, WindowEvent, WorkerStateEventYou can define event handlers in your application30Tecniche di programmazioneA.A. 2014/2015

Properties Extension of the Java Beans convention Encapsulate properties of an object May be used also outside JavaFXDifferent types (string, number, object, collection, .)Set/GetObserve changesSupports lazy evaluationEach Node has alarge set of Properties31Tecniche di programmazioneA.A. 2014/2015

Bindings Automatically connect («bind») one Property to anotherProperty Whenever the source property changes, the bound one isautomatically updatedMultiple bindings are supportedLazy evaluation is supportedBindings may also involve computations (arithmetic operators,if-then-else, string concatenation, .) that are automaticallyevaluatedMay be used to automate UIMay be used to connect the Model with the View32Tecniche di programmazioneA.A. 2014/2015

The Scene graphIntroduction to JavaFX

Nodes Root node: top level containerIntermediate nodes: Leaf (terminal) nodes: ContainersLayout managersUI Composite controlsShapesUI ControlsOrganized as a Hierarchical tree34Tecniche di programmazioneA.A. 2014/2015

s eButtonLabelListViewControlTitledPaneFocus eGridPaneJavaDocis iewTextTecniche di programmazioneA.A. 2014/2015

Exploring Controls and Examples JavaFX Ensemble demoapplicationDownload from Oraclesite: JavaFX Demos andSamples DownloadsRun Ensemble.jnlp36Tecniche di programmazioneA.A. 2014/2015

UI Form Controls Controls may becombined to construct«Forms»Control Nodes have avalue property May be linked to applicationcodeControl Nodes generateUI Events 37Button: ActionEventText: ActionEvent,KeyTyped, KeyPressed,MouseClicked, .Tecniche di programmazioneA.A. 2014/2015

38Tecniche di programmazioneA.A. 2014/2015

Layout Class Hierarchy Group: Region: Doesn’t perform any positioning of children.To statically assemble a collection of nodes in fixed positionsTo apply an effect or transform to that collection.base class for all general purpose layout panesresizable and stylable via CSSSupports dynamic layout by sizing and positioning childrenControl: the base class for all skinnable controlsresizable and subclasses are all stylable via CSSControls delegate layout to their skins (which are Regions)Each layout Control subclass provides API for adding content in theappropriate place within its skin 39you do not add children to a control directly.Tecniche di programmazioneA.A. 2014/2015

40Tecniche di programmazioneA.A. 2014/2015

41Tecniche di programmazioneA.A. 2014/2015

42Tecniche di programmazioneA.A. 2014/2015

43Tecniche di programmazioneA.A. 2014/2015

44Tecniche di programmazioneA.A. 2014/2015

45Tecniche di programmazioneA.A. 2014/2015

46Tecniche di programmazioneA.A. 2014/2015

47Tecniche di programmazioneA.A. 2014/2015

Creating the Scene Graph The Java way Create Control NodesSet properties to new nodesAdd new nodes to parent nodeWith Constructors and/or with BuildersThe FXML way 48Create a FXML fileDefine Nodes and Properties in FXMLLoad the FXML(Optionally, add new nodes/properties the Java way)Tecniche di programmazioneA.A. 2014/2015

Example: one text input fieldConstructorsTextField text new TextField("Text");text.setMaxSize(140, 20);root.getChildren().add(text);TextField text (140).text("Text").build() ;Buildersroot.getChildren().add(text);49Tecniche di programmazioneA.A. 2014/2015

public class HelloDevoxx extends Application {public static void main(String[] args){launch(args);}@Overridepublic void start(Stage primaryStage){primaryStage.setTitle("Hello Devoxx");Group root new Group();Scene scene new Scene(root, 400, 250,Color.ALICEBLUE);Text text new new Font(30));text.setText("Hello .setScene(scene);primaryStage.show();}}50Tecniche di programmazioneA.A. 2014/2015

public void start(Stage primaryStage){primaryStage.setTitle("Hello te().x(105).y(120).text("Hello Devoxx").font(new show();}51Tecniche di programmazioneA.A. 2014/2015

The FXML way. XML-based formatNested tree of XML Elements, corresponding to NodesXML Attributes corresponding to (initial) properties ofnodes JavaFX Scene Builder is a GUI for creating FXML files The FXMLLoader class reads a FXML file and creates allthe Nodes52Tecniche di programmazioneA.A. 2014/2015

Example53Tecniche di programmazioneA.A. 2014/2015

JavaFX Scene Builder54Tecniche di programmazioneA.A. 2014/2015

FXMLLoader@Overridepublic void start(Stage stage) throws Exception {Parent root FXMLLoader.load(getClass().getResource("fxml example.fxml"));stage.setTitle("FXML Welcome");stage.setScene(new Scene(root, 300, 275));stage.show();}55Tecniche di programmazioneA.A. 2014/2015

Linking FXML and Java FXML element may have an associated attribute fx:idNodes may be later retrieved by public Node lookup(java.lang.String selector)Finds a node with a specified ID in the current sub-treeExample: scene.lookup("#myId");Node references can also be «injected» using the@FXML annotation (see later)56Tecniche di programmazioneA.A. 2014/2015

EventsIntroduction to JavaFX

Interacting with Nodes In JavaFX applications, events are notifications thatsomething has happened. An event represents an occurrence of something of interest tothe applicationAs a user clicks a button, presses a key, moves a mouse, orperforms other actions, events are dispatched.Registered event filters and event handlers within theapplication 58receive the event andprovide a response.Tecniche di programmazioneA.A. 2014/2015

What is an event?59Tecniche di programmazioneA.A. 2014/2015

Event propagation Events are generated on the source nodeEvents propagated in the scene graph hierarchy («dispatchchain»), in two phases Dispatching: downwards, from root to source node Bubbling: upwards, from source node to root Processes Event Filters registered in the nodesProcesses Event Handlers registered in the nodesIf you want an application to be notifiedwhen an event occurs, register a filteror a handler for the eventHandlers may “consume” the event60Tecniche di programmazioneA.A. 2014/2015

Event Handlers Implements the EventHandler interfaceExecuted during the event bubbling phase.If does not consume the event, it is propagated to theparent.A node can register more than one handler.Handlers for a specific event type are executed beforehandlers for generic event types. For example, a handler for the KeyEvent.KEY TYPED event iscalled before the handler for the InputEvent.ANY event.To consume an event, call the consume() method61Tecniche di programmazioneA.A. 2014/2015

Registering Event Handlers setOnEvent-type(EventHandler ? super event-class value ) Event-Type Event-class The class that defines the event type (e.g., KeyEvent , MouseEvent, .)Value 62The type of event that the handler processes (e.g. setOnKeyTyped,setOnMouseClicked, .)The event handler for event-class (or for one of its super classes)Must implement: public void handle(ActionEvent event)May be a regular class or an anonymous inline classTecniche di programmazioneA.A. 2014/2015

Exampleclass ButtonActionHandler implementsjavafx.event.EventHandler ActionEvent {Event Handlerpublic ButtonActionHandler (/*params*/) {// constructor - if needed}@Overridepublic void handle(ActionEvent event) {Button b (Button)event.getSource() ;//.do somethingString buttonText b.getText() ;// .}}RegistrationButton btn new Button() ;btn.setOnAction(new ButtonActionHandler()) ;63Tecniche di programmazioneA.A. 2014/2015

Example (inline definition)Registration &Anonymous event handlerbtn.setOnAction(new EventHandler ActionEvent () {public void handle(ActionEvent event) {System.out.println("Hello World");}});64Tecniche di programmazioneA.A. 2014/2015

Model-View-ControllerJavaFX programming

Application complexity and MVC Interactive, graphical applications exhibit complexinteraction patternsFlow of control is in the hand of the userActions are mainly asynchronousHow to organize the program?Where to store data?How to decouple application logic from interface details?How to keep in sync the inner data with the visibileinterface?66Tecniche di programmazioneA.A. 2014/2015

Media Player example67Tecniche di programmazioneA.A. 2014/2015

MVC pattern defined68Tecniche di programmazioneA.A. 2014/2015

Normal life-cycle of interaction69Tecniche di programmazioneA.A. 2014/2015

Mapping concepts to JavaFX View: presenting the UI Controller: reacting to user actions FXMLThe Nodes in the Scene GraphSet of event handlersModel: handling the data 70Class(es) including dataPersistent data in Data BasesTecniche di programmazioneA.A. 2014/2015

Design Exercise Imagine an application managing a list of items (e.g.,names)Different items in the user interface should manage thesame set of data, with different criteria and actionsWhere do you declare the data class?Which class should have access to which?Who creates what objects?71Tecniche di programmazioneA.A. 2014/2015

A possiblesolution72Tecniche di programmazioneA.A. 2014/2015

The Controller in FXMLJavaFX programming

The Controller in FXML Several attributes in FXML help in the definition of theController behavior associated to a scene Identification of the Controller classInjection of Node identifiers (references)Registration of event handlersAdditionally, the JavaFX Scene Builder may generate a«controller skeleton» for inclusion in the project74Tecniche di programmazioneA.A. 2014/2015

Defining the Controller class The Root element of the scenegraph may specify a fx:controller attribute 75 BorderPaneid "BorderPane"xmlns:fx "http://javafx.com/fxml"fx:controller "it.polito.tecnprogr.RuzzleController" Tecniche di programmazioneA.A. 2014/2015

fx:controller attribute Associate a "controller" class with an FXML document Automatically create the instance when FXML is loadedShould include event handler methodsMay include an initialize() method 76public void initialize();called once when the contents of its associated document havebeen completely loadedany necessary post-processing on the contentTecniche di programmazioneA.A. 2014/2015

Accessing the controller instance The Application often needs to communicate with thecontroller object E.g., to call setModel()FXMLLoader provides this informationURL location getClass().getResource("example.fxml");FXMLLoader fxmlLoader new FXMLLoader(location);Pane root (Pane)fxmlLoader.load();MyController controller e di programmazioneA.A. 2014/2015

Injection of Node references The controller code may directly access various Nodes inthe associated scene graphThe attribute @FXML associates a Node variable withthe corresponding node, with the same fx:id value as thevariable name No more error-prone «lookup» calls.Local variables in the controller instanceTry:View Show Sample Controller Skeleton on theScene Builder!@FXML // fx:id "theTitle"private Label theTitle;78Tecniche di programmazioneA.A. 2014/2015

Registration of Event Handlers In FXML, you may set a event handlerthrough attributes onAction, onKeyTyped, onMouseClicked,. hundreds more .The value should be the #name of amethod in the controller class With the right signature for the eventtype Button fx:id "cercaBtn"onAction "#doCercaParola"text "Cerca" / 79@FXMLvoid doCercaParola (ActionEvent event ) {Tecniche di programmazioneA.A. 2014/2015

ResourcesIntroduction to JavaFX

Resources Official Documents x.htmlBlogs ity/javafxTecniche di programmazioneA.A. 2014/2015

Resources API Slides/Tips z/getting-started-javafxTutorials/Articles avafx2-0-layout-aclass-tour/Examples (Downloads) 85JavaFX Demos and Samples, wnloads/jdk7downloads-1880260.htmlTecniche di programmazioneA.A. 2014/2015

Resources FXML Controller Charts cfiles/introduction to fxml.html#controllersUsing JavaFX Charts xpub-charts.htmBooks 86Head First Design Patterns, chapter 12Tecniche di programmazioneA.A. 2014/2015

Resources Properties and Bindings 7/29/properties-andbindings-in-javafx/Tecniche di programmazioneA.A. 2014/2015

Licenza d’uso Queste diapositive sono distribuite con licenza Creative Commons“Attribuzione - Non commerciale - Condividi allo stesso modo (CCBY-NC-SA)”Sei libero: Alle seguenti condizioni: di riprodurre, distribuire, comunicare al pubblico, esporre in pubblico,rappresentare, eseguire e recitare quest'operadi modificare quest'operaAttribuzione — Devi attribuire la paternità dell'opera agli autorioriginali e in modo tale da non suggerire che essi avallino te o il modo incui tu usi l'opera.Non commerciale — Non puoi usare quest'opera per finicommerciali.Condividi allo stesso modo — Se alteri o trasformi quest'opera, o sela usi per crearne un'altra, puoi distribuire l'opera risultante solo con unalicenza identica o equivalente a a/3.0/88Tecniche di programmazioneA.A. 2014/2015

JavaFX 2.x 6 Tecniche di programmazione A.A. 2014/2015 Redesigned from scratch The JavaFX 2.x framework is entirely written in Java For visual layout, an XML file may also be used (called FXML) Graphic appearance borrows from web-standard CSS style sheets UI programming is based on easy to handle events a

Related Documents:

.media - in Default VM Arguments. Note that your JavaFX library location can be different depending on the location that you unzipped. METHOD III: From CMD Prompt: java --module-path "C:\Users\selim\Documents\javafx-sdk-11.0.2\lib" --add-m

This tutorial is a compilation of three documents that were previously delivered with the JavaFX 2.x documentation set: JavaFX Overview, JavaFX Architecture, and Getting Started with JavaFX.

This chapter describes how to add JavaFX co ntent into a Swing application and how to use threads correctly when both Swing and JavaFX content operate within a single application. JavaFX SDK provides the JFXPanel class, which is located in the javafx.embed.swing package and enables you to embed

Oct 10, 2011 · Support for ARM platforms has also been made available with JavaFX 8. JDK for ARM includes the base, graphics and controls components of JavaFX. To install JavaFX install your chosen version of the Java Runtime environment and Java Development kit. Features offered by JavaFX include

General rules 8 Tecniche di programmazione A.A. 2020/2021 A JavaFX application extends javafx.application.Application The main() method should call Application.launch() The start() method is the main entry point for all JavaFX applications Called with a Stage connected to the Operating System's window The content of the scene is represented as a hierarchical

What You Will Learn 1 1.1 Background Basics 2 JavaFX Integration 2 1.2 The NetBeans Platform: The Big Picture 3 Module System API 3 . 2.4 Improving the User Experience 63 2.5 Concurrency and Thread Safety 68 . 3.2 Building JavaFX Programs 87 Creating a JavaFX Application 88 Java APIs 88

Database Operations in JavaFX . At first, part of JavaFX tutorial series, we created a sample JavaFX project, designed the draft version of the UI and set up an Oracle XE database. In this post, we will create controller, model, DAO, and Util classes to do DB operations. Before starting to code, I want to give more information about our example .

The section on illustration greatly benefited from Lys Drewett s ten years experience teaching archaeological illustration at the Institute of Archaeology and as illustrator on all my archaeological projects. Most of the illustrations derive from my field projects but, where not, these are gratefully acknowledged under the illustration. To any other archaeologists who feel I may have used .