Build a JavaFX User Interface

JavaFX APIs provide a set of graphics and media packages that enable developers to design, create, test, debug, and deploy rich client applications that operate consistently across diverse platforms.

JavaFX is built on a layered architecture of interrelating components that supports high-performance user interfaces (UIs) that feature audio, video, graphics, and animation. The JavaFX architecture provides APIs, graphics pipelines, web and media engines, and cross-platform portability.

The JavaFX scene graph is a hierarchical tree of nodes that represents all of the elements in an application UI (scene) and their relationships. Developers start JavaFX application development by using the JavaFX APIs to construct the scene graph. With the exception of the root node of a scene graph, which has no parent, each node in a scene graph has one parent and zero or more children. Nodes in a scene graph can handle input and be rendered. The javafx.scene.Node class has properties and methods to define and manage the nodes in a scene graph.

 

The JavaFX code for this lesson creates the simple application shown below. The window on the left displays when you start the application, and the window on the right displays when you click the Click Me button. Click the Click Again button to go back to the original window on the left.

The example was built with the following software configuration:

  • JDK1.8.0_45
  • Apache Tomcat v8.0.36
  • Eclipse Mars.2 Release (4.6.0)

JavaFXUI Example

  1. Build the Example in Eclipse
  2. Enable JavaFX in Eclipse
  3. Add a Cascading Style Sheet
  4. Code Overview
  5. Clean, Build, and Run the Example

1. Build the Example in Eclipse

  1. In Eclipse, select New > File > Project > Java Project
  2. Click Next
  3. Provide Name: JavaFXApp and click Next
  4. Click Finish
  5. In Eclipse, expand the JavaFXApp and locate the src folder
  6. Right-click the src folder and select New > Package
  7. In the Java Package dialog, provide the name essentialsjpl
  8. Click Finish
  9. Right click the package folder and select New > Class
  10. In the Java Class dialog, type the class name JavaFXUI
  11. Click Finish
  12. Copy and paste the following code into the JavaFXUI class file
    If you have package errors, you can fix them in the next section, Enable JavaFX in Eclipse.
package essentialsjpl;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class JavaFXUI extends Application {
  TextField textField;
  Label text, clicked;
  Button button, clickButton;
  BorderPane BPane;
  private boolean _clickMeMode = true;

  @Override
  public void start (Stage primaryStage) {
  //Create BorderPane
  BPane = new BorderPane();
  BPane.setId("grid-pane");
  BPane.getStyleClass().add("pane-styles");

  //Create Scene and add border pane
  Scene Scene = new Scene(BPane, 200, 100);
  Scene.getStylesheets().add(this.getClass().getResource
  ("EssentialsJPL.css").toExternalForm());

  //Create the stage and add the scene
  primaryStage.setTitle("Example");
  primaryStage.setScene(Scene);

  text = new Label("I'm a simple program.");
  button = new Button("Click Me");
  button.setOnAction(new EventHandler<ActionEvent>() {
  @Override
  public void handle(ActionEvent event) {
  Object source = event.getSource();
  String s = null;
  //Variable to display text read from file
  if (source == button) {
    if (_clickMeMode) {
     text.setText("Button Clicked");
     button.setText("Click Again");
     _clickMeMode = false;
    } else {
      text.setText("I’m a Simple Program");
      button.setText("Click Me");
     _clickMeMode = true;
    }
  }
 }
});
 //Set positions for each control in the BorderPane
 BPane.setTop(text);
 BPane.setBottom(button);

 //Show the scene
 primaryStage.show();
}
//main method
  public static void main(String[] args){
  launch(args);
}
}

2. Enable JavaFX in Eclipse

JavaFX is not by default enabled on Eclipse. The easiest way to enable JavaFX is to add the path to jfxrt.jar to your build path.

  1. Right click the UIBakerRESTJerseyClient project.
  2. In the drop-down menu, select Build Path > Configure Build Path.
  3. In the Libraries tab, select Add External JARs.
  4. Add the path to your jfxrt.jar file, for example:
    C:\Program Files (x86)\Java\jre1.8.0_91\lib\ext.javafxconfigure

Alternately and especially if you plan to do a lot of JavaFX programming, you can install e(fx)clipse, which is a plugin for Eclipse that supports JavaFX. See the following link for more information: https://www.eclipse.org/efxclipse/install.html#for-the-lazy.

3. Add a Cascading Style Sheet

The look and feel of JavaFX applications can be customized. Cascading Style Sheets (CSS) contain style definitions that control the look of user interface elements. CSS also separate appearance and style from implementation so that developers can concentrate on coding. Graphic designers can easily customize the appearance and style of the application through the CSS.

Line 26: Tells the border pane control to use the pane-styles definitions to style the border pane and all of its controls.

BPane.getStyleClass().add("pane-styles");

Line 30: Adds the EssentialsJPL.css cascading style sheet (css) to the example program.

Scene.getStylesheets().add(this.getClass().getResource
("EssentialsJPL.css").toExternalForm());panel = new JPanel();

The example program uses the following style definitions. See Skinning JavaFX Applications with CSS at http://docs.oracle.com/javafx/2/css_tutorial/jfxpub-css_tutorial.htm and The CSS Reference Guide at http://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html for more information.

You must create and add this style sheet to your project:

  1. Right-click the essentialsjpl package and select File > Other
  2. Highlight CSS File under Web > CSS File and click Next
  3. Name the CSS fIle EssentialsJPL.css and click Finish.
  4. Locate the CSS file in your project and open it.
    It belongs under the essentialsjpl package. If it is not there, move it.
  5. Change the top line from @CHARSET “ISO-8859-1”; to [@CHARSET “ISO-8859-1”;]
  6. Copy and paste the following style sheet definitions into the css file:
[@CHARSET "ISO-8859-1";]
/* Global style definitions. Apply to all UI elements in the application. */
.root {
  display: block;
  -fx-font-size: 14px "Serif";
  -fx-font-family: Tahoma;
  -fx-font-weight: NORMAL;
}
/* Border pane style definitions. Apply to all UI elements in the border pane.
The pane-styles style definition was added to the border pane on Line 26. */
.pane-styles {
  -fx-background-color: rgb(87, 206, 248);
  -fx-hgap: 2px;
  -fx-vgap: 2px;
  -fx-padding: 5px;
  -fx-grid-lines-visible: false;
}
/* Labels in the border pane have this additional style definition. */
.pane-styles .label {
  -fx-padding: 10 10 10 0;
}
/* Text fields in the border pane have these additional style definitions. */
.pane-styles .text-field {
  -fx-background-color: #999999, #336699,
  linear-gradient(to bottom, #fff 0%, #ccc 100%);
  -fx-background-insets: 1px, 2px, 3px;
  -background-radius: 0px 0px 9px 0px, 0px 0px 8px 0px, 0px 0px 8px 0px;
  -padding: 5px;
  -fx-display-caret: true;
}
/* buttons added to the border pane have these additional style definitions. */
.pane-styles .button {
  -fx-background-color: #707070,
  linear-gradient(#fcfcfc, #f3f3f3),
  linear-gradient(#f2f2f2 0%, #ebebeb 49%, #dddddd 50%, #cfcfcf 100%);
  -fx-background-insets: 1px, 2px, 3px;
  -fx-padding: 3px 20px 3px 20px;
}

4. Code Overview

The following are the important things to know about the basic structure of a JavaFX application:

  • Line 14: JavaFX class extends the javafx.application.Application class.
  • Line22: the start method is the main entry point for all JavaFX applications.
  • Lines 23 to 34: A JavaFX application defines the user interface container with a stage and a scene. The stage is the top-level JavaFX container. The stage contains a scene, and the scene is the container for all content.
  • Lines 23 to 26: A border pane layout control is added to the scene to organize the other controls in the top, left, right, bottom, and center positions shown here.

 border2

  • Lines 23 to 26: The root node contains one child node, the border pane control.
  • The main method is not required for JavaFX applications when the JAR file for the application is created with the JavaFX Packager tool, which embeds the JavaFX Launcher in the JAR file.It is useful to include the main method so you can run JAR files that were created without the JavaFX Launcher, such as when using an IDE in which the JavaFX tools are not fully integrated. Also, Swing applications that embed JavaFX code require the main method.

Instance Variables

Lines 15-19 declare the JavaFX classes needed by the example program. These are instance variables (or fields) that can be accessed by any method in the instantiated class. In this example, they are built in the start method and accessed in the button.setOnAction method.

The private boolean _clickMeMode variable is an instance variable that is only accessible to the JavaFXUI class. It is used in the button.setOnAction method to find out whether the button has been clicked.

TextField textField;
Label text, clicked;
Button button, clickButton;
BorderPane BPane;
private boolean _clickMeMode = true;

Action Event Handling

Lines 38 to 56 handle the button event when the user clicks the Click Me and Click Again buttons, which generates an action event. When a button click action event occurs, the Java platform services pass the button click action to the setOnAction method.

The Java platform passes an event object to the handle method. The event object represents an action event that occurred. The handle method has an if statement to determine whether the button component fired the action event and to test the _clickMeMode variable to find out the state of the button component.

If the button component is waiting to be clicked, the label and button text change to reflect that the button was just clicked. If the button component has been clicked, the label and button text change to invite another click.

button = new Button("Click Me");
button.setOnAction(new EventHandler() {
  @Override
  public void handle(ActionEvent event) {
     Object source = event.getSource();
     String s = null;
     //Variable to display text read from file
     if (source == button) {
       if (_clickMeMode) {
         text.setText("Button Clicked");
         button.setText("Click Again");
         _clickMeMode = false;
       } else {
         text.setText("I’m a Simple Program");
         button.setText("Click Me");
         _clickMeMode = true;
       }
     }
 }
});

5. Clean, Build, and Run the Example

  1. Save all of your files.
  2. Select the JavaFXApp project and select Project > Clean
  3. Select the JavaFXApp project and select Project > Build Project
  4. Right click the JavaFXApp project and select Run As > Java Application
Advertisements
Build a JavaFX User Interface

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s