Build Desktop application software using Java Tutorial | Sample Examples -Part 2

By | September 15, 2016

In the previous part, we saw a very basic template for the desktop application using JavaFX. Lets go ahead with the following sections today in this part :

  • Handle User Events
  • Anonymous Inner Classes And Lambda Expressions
  • Switching Scenes
  • Creating Alert Boxes

Handle User Events

We have seen previously how to create a button on the scene. But it did nothing when we clicked it. Lets add a functionality to it by handling the click event on the button.

Replace the previous Main.Java with the following:

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application implements EventHandler<ActionEvent> {

    Button button;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Title of Window");
        button = new Button();
        button.setText("Hey baby");

        //This class will handle the button events
        button.setOnAction(this);

        StackPane layout = new StackPane();
        layout.getChildren().add(button);
        Scene scene = new Scene(layout, 300, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    //When button is clicked, handle() gets called
    //Button click is an ActionEvent (also MouseEvents, TouchEvents, etc...)
    @Override
    public void handle(ActionEvent event) {
        if (event.getSource() == button) 
            System.out.println("Hey Charlie!");
    }

}

We have implemented EventHandler interface in the Main.java this time. So this class can simply handle all the events for the scene.

We need to override the hande() method of the EventHandler interface in Main class. This method handles all type of events for the application. So we need to check which on which layout has the current event occured.  So we added a check for the button  in the handle() method for all the events called on buttons.

Now run the Main.Java file as Java Application and click on the button. You will see ‘Hey Charlie!’ printed on the console.

Thus we have handled click events for the button.

 

Handle Click event JavaFX

Anonymous Inner Classes And Lambda Expressions

The above example we saw for event handling had too much work to be done for just a single event.  Lets look at a different implementation for the same task as before using Lambda Expressions

Replace the Main.Java file with the following:


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {

	Button button;

	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage primaryStage) {
		primaryStage.setTitle("Title of Window");
		button = new Button();
		button.setText("Click Me");

		button.setOnAction(e -> {
			System.out.println("dsa dsa dsa !");
			System.out.println("Lambda expressions are awesome!");
		});

		/*
		 * button.setOnAction(new EventHandler<ActionEvent>() {
		 * 
		 * @Override public void handle(ActionEvent event) {
		 * System.out.println("Handle event using anonymous inner classes"); }
		 * });
		 */

		StackPane layout = new StackPane();
		layout.getChildren().add(button);
		Scene scene = new Scene(layout, 300, 250);
		primaryStage.setScene(scene);
		primaryStage.show();
	}

}

Look at the commented section of the code above. The commented section is another way of doing the same EventHandling using anonymous class. You might be already familiar with that method.
The uncommented setOnAction() method which has been called uses Lambda Expressions for quickly handling the event. This feature has been added in JDK8 only.  So you might face syntax errors if you are using lower versions of JDK.

Switching Scenes

Now lets learn about changing the scene i.e whole layout of the stage of our application. Its similar to switching fragments in an Android Application.

For example : You click a button to go to next page or previous page.

Now Replace the Main.Java with:

import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;

public class Main extends Application {

    Stage window;
    Scene scene1, scene2;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        window = primaryStage;

        //Button 1
        Label label1 = new Label("Welcome to the first scene!");
        Button button1 = new Button("Go to scene 2");
        button1.setOnAction(e -> window.setScene(scene2));

        //Layout 1 - children laid out in vertical column
        VBox layout1 = new VBox(20);
        layout1.getChildren().addAll(label1, button1);
        scene1 = new Scene(layout1, 200, 200);


        //Button 2
        Button button2 = new Button("This sucks, go back to scene 1");
        button2.setOnAction(e -> window.setScene(scene1));

        //Layout 2
        StackPane layout2 = new StackPane();
        layout2.getChildren().add(button2);
        scene2 = new Scene(layout2, 600, 300);

        //Display scene 1 at first
        window.setScene(scene1);
        window.setTitle("Title Here");
        window.show();
    }

}

VBox is another type of layout similar to Stackpane. VBox stands for Vertical Box. HBox stands for Horizontal Box. VBox adds Layouts in vertically stacked manner while HBox adds layout in horizontal way.

scenes JAVAFX

Look at the above two screenshots for the scenes. You can also change the resolution of the scene when switching.

Creating Alert Boxes

Lets create alert box in our applicaton.

  • Alert Boxes are used for showing a warning dialog.
  • Opening settings window and so on..

Alert box in JavaFX is simply another window similar to our original window of the application itself.

Create a new Class named AlertBox.java :


import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;

public class AlertBox {

    public static void display(String title, String message) {
        Stage window = new Stage();

        //Block events to other windows
        window.initModality(Modality.APPLICATION_MODAL);
        window.setTitle(title);
        window.setMinWidth(250);

        Label label = new Label();
        label.setText(message);
        Button closeButton = new Button("Close this window");
        closeButton.setOnAction(e -> window.close());

        VBox layout = new VBox(10);
        layout.getChildren().addAll(label, closeButton);
        layout.setAlignment(Pos.CENTER);

        //Display window and wait for it to be closed before returning
        Scene scene = new Scene(layout);
        window.setScene(scene);
        window.showAndWait();
    }

}
1

This class can simply be used whenever and wherever you need an alertBox to be shown.
Lets show the alert Box in Main.java:
1
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {

    Stage window;
    Button button;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        window = primaryStage;
        window.setTitle("Tutorials Face");
        button = new Button("Click Me");

        button.setOnAction(e -> AlertBox.display("Title of Window", "Wow this alert box is awesome!"));

        StackPane layout = new StackPane();
        layout.getChildren().add(button);
        Scene scene = new Scene(layout, 300, 250);
        window.setScene(scene);
        window.show();
    }

}

We have simply called the static method defined in AlertBox.java to show a new window.
ALERT Box JavaFX

Look at the above screenshot how the alertBox is displayed as a new window.
The layout can always be made beautiful :p

We will see the remains topics in the next part.

1,886 total views, 10 views today

(Visited 805 times, 6 visits today)