On this section of my series of JavaFX tutorial, we will be showing on the form creation which is very common in developing a desktop application. We will be showing on how to layout the form, add controls, and events.

Creating a Form in JavaFX

For the rest of all my javafx tutorial, I will be using mostly netbeans thus if you have not installed it yet, please do so. If you have not yet created your first application in JavaFX, it would be better to start in Hello World tutorial first which serves as the foundation in creating more advanced application.

A good example for demonstration is a simple tax calculator. It would have labels, textbox, and button. Pressing the button will calculate the tax and will display the result as a message on the form. Please follow these simple steps

  1. Create a new JavaFX Project and named it TaxCalculator.
  2. A TaxCalculator.java will be generated automatically and it will show the hello world template.
  3. Remove all the codes on the start method
  4. Now first and foremost set the title of the form “JavaFX Tax Calculator” which will appear at the left top most part of the form
    primaryStage.setTitle("JavaFX Tax Calculator");
  5. And make the stage visible using the command
    primaryStage.show();
  6. The code that we have as this moment would be able to generate the following if you try to run it
    JavaFX Tax Calculator Blank Form

    JavaFX Tax Calculator Blank Form

JavaFX Panel Layout

Now we have to decide what to use as a layout on our form. Since the GridPane Layout provides a flexible grid of rows and columns which we need in layouting the controls. Moving back on our TaxCalculator form perform the following after the setTitle on start method.

  1. Initialize the Form Layout by declaring the following
    GridPane pane = new GridPane();
  2. Set the alignment
    pane.setAlignment(Pos.CENTER);
  3. Set the gap between controls
    pane.setHgap(10);
    pane.setVgap(10);
  4. Set the padding. Make a note that the padding are spaces around the edges of the GridPane. The Insets follow this order; top,right, bottom, left. Let’ set 25 pixels on every side.
    pane.setPadding(new Insets(25, 25, 25, 25));
  5. Now initialize the scene and also its size.
            Scene scene = new Scene(pane, 300, 275);
            primaryStage.setScene(scene);

Adding the Tax Calculator Form Elements

Now we can populate the scene with the necessary controls

  1. First and foremost we have to add a welcome text by adding the following after the initialization of scene and before the setScene code.
    Text sceneTitle = new Text("Tax Calculator");
    sceneTitle.setFont(Font.font("Arial", FontWeight.NORMAL,20));
    pane.add(sceneTitle, 0, 0, 2, 1);
  2. After adding the title text, we have to add the label Income and it’s corresponding textField. Make a note that we are adding these elements using the pane.add(element,column,row). The counting of rows and columns starts at 0.
    Label total = new Label("Income:");
    pane.add(total, 0, 1);
    TextField totalField = new TextField();
    pane.add(totalField, 1, 1);
    Label percent = new Label("% Tax:");
    pane.add(percent,0,2);
    TextField percentField = new TextField();
    pane.add(percentField, 1, 2);
  3. Now that we have the fields layout on our scene, we now add the control button to Calculate the Tax incurred.
    Button calculateButton = new Button("Calculate");        
    HBox hbox = new HBox(10);
    hbox.setAlignment(Pos.BOTTOM_RIGHT);
    hbox.getChildren().add(calculateButton);
    pane.add(hbox, 1, 4);
  4. Add the message text where the result (tax incurred) would be displayed.
    final Text taxMessage = new Text();
    pane.add(taxMessage, 1, 6);

JavaFX Button Event Handling

We are done on the layout of elements on our form. Now we have to add functionality on the event when the button is pressed. We are expecting that if we press the button, tax incurred will be calculated using the value input on the text field that we have already put on our JavaFX form. Add the following code block just before the primaryStage.setScene(scene);

        calculateButton.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                Double income = Double.parseDouble(totalField.getText());
                Double tax = Double.parseDouble(percentField.getText())/100;
                taxMessage.setText("Tax incurred:"+income*tax);
            }
        });

The code fragment above basically the action taken when the button is pressed. It calculate sthe tax incurred and display it on the taxMessage Text element. Since we are getting and parsing the values of the textField totalField and percentField, we need to make the declaration final. Please see below the full source code of JavaFX Tax Calculator.

Tax Calculator JavaFX Source Code

package taxcalculator;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 *
 * @author ryan
 * JavaFX Tax Calculator Form Layout
 * and Basic JavaFX Button Event Handler
 */
public class TaxCalculator extends Application {

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("JavaFX Tax Calculator");
        GridPane pane = new GridPane();
        pane.setAlignment(Pos.CENTER);
        pane.setHgap(10);
        pane.setVgap(10);
        pane.setPadding(new Insets(25, 25, 25, 25));
        Scene scene = new Scene(pane, 300, 275);

        Text sceneTitle = new Text("Tax Calculator");
        sceneTitle.setFont(Font.font("Arial", FontWeight.NORMAL,20));
        pane.add(sceneTitle, 0, 0, 2, 1);
        Label total = new Label("Income:");
        pane.add(total, 0, 1);
        final TextField totalField = new TextField();
        pane.add(totalField, 1, 1);
        Label percent = new Label("% Tax:");
        pane.add(percent,0,2);
        final TextField percentField = new TextField();
        pane.add(percentField, 1, 2);

        Button calculateButton = new Button("Calculate");        
        HBox hbox = new HBox(10);
        hbox.setAlignment(Pos.BOTTOM_RIGHT);
        hbox.getChildren().add(calculateButton);
        pane.add(hbox, 1, 4);

        final Text taxMessage = new Text();
        pane.add(taxMessage, 1, 6);

        calculateButton.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                Double income = Double.parseDouble(totalField.getText());
                Double tax = Double.parseDouble(percentField.getText())/100;
                taxMessage.setText("Tax incurred:"+income*tax);
            }
        });

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * The main() method is ignored in correctly deployed JavaFX application.
     * main() serves only as fallback in case the application can not be
     * launched through deployment artifacts, e.g., in IDEs with limited FX
     * support. NetBeans ignores main().
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}

Running the Source Code Above will display the following Desktop Application

JavaFX Tax Calculator

JavaFX Tax Calculator