Wednesday, 9 May 2018

JavaFX: Working with Label widget

Label is used to display non-editable text in the user interface.

How to create Label?
Label class provides below constructors to define label widget.

public Label()
public Label(String text)
public Label(String text, Node graphic)

Ex
Label label1 = new Label();
label1.setText("Hello JavaFX");

Label label2 = new Label("Good Morning");

InputStream is = new FileInputStream(imageFilePath);
Image image = new Image(is);
Label label3 = new Label("Java Icon", new ImageView(image));

Find the below working application.

LabelApp.java
package com.sample.demos;

import static javafx.geometry.Pos.CENTER;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class LabelApp extends Application {

 private static String imageFilePath = "C:\\Users\\krishna\\Documents\\Study\\javaFX\\javaIcon.png";

 @Override
 public void start(Stage primaryStage) throws FileNotFoundException {

  Label label1 = new Label();
  label1.setText("Hello JavaFX");

  Label label2 = new Label("Good Morning");

  InputStream is = new FileInputStream(imageFilePath);
  Image image = new Image(is);
  Label label3 = new Label("Java Icon", new ImageView(image));

  VBox vBox = new VBox(10, label1, label2, label3);
  vBox.setAlignment(CENTER);

  Scene scene = new Scene(vBox, 600, 600);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("JavaFX Label Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFx.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(LabelApp.class, args);
 }
}

When you ran above application, you can able to see below window.








      Working with Label widget
      Set label text color
      Set gap between text and graphic image
      Align label text
      setContentDisplay: Set the position of graphic relative to text
      setFont: Set label font
      Wrapping up the text
      Render big strings in limited space
      Applying Effects
      Event handling


Previous                                                 Next                                                 Home

Chapter 2: JavaFX UI Controls

In chapter1 of the tutorial, I explained basics of JavaFX. In this chapter, you are going to learn the UI controls provided by JavaFX.

I am going to explain below UI controls in detail.

·       Label
·       Button
·       Radio Button
·       Toggle Button
·       Checkbox
·       Choice Box
·       Text Field
·       Password Field
·       Scroll Bar
·       Scroll Pane
·       List View
·       Table View
·       Tree View
·       TreeTable View
·       Combo Box
·       Separator
·       Slider
·       Hyperlink
·       Tooltip
·       HTML Editor
·       Titled Pane and Accordion
·       Menu
·       Color Picker
·       Date Picker
·       Pagination Control
·       File Chooser
·       Customization of UI Controls
·       UI Controls on the Embedded Platforms


Previous                                                 Next                                                 Home

Why should a private constructor throw an exception?

One of my friend got this interview question. Interviewer asked him that a class  ‘X’ has only one constructor, and it is throwing exception like below.

class X{
 
 private X() {
  throw new IllegalStateException("No instances!");
 }

        ...
 ...
}

Interviewer asked him, tell me the situation, where can I use above kind of class?

Why the constructor is private?
If you do not want to create an instance of class from outside, you can make the constructor private. But if you do not throw an exception from the constructor, the code inside the class X, can create an instance of the class.
class X{
 
 private X() {
  
 }
 
 public static X getInstance() {
  return new X();
 }
}

You can get an instance of class X, by calling getInstance method.

On what cases the constructor should throw an exception?
Suppose if a class has only static methods, then no point in creating an object to that class. You can always use the class name to access the static methods. By throwing an exception, we can prevent accidental invocation of the constructor from within the class.

This scenario make sense for the classes java.lang.Math, java.util.Arrays. These classes has only static methods.


You may like


Exercise1: JavaFX: Print multiplication table

Whenever user clicks on the button, display multiplication table of 2.

Find the below working application.

NumberUtil.java
package com.sample.demos;

public class NumberUtil {

 public static String getMultiplictionTable(int n, int until){
  StringBuilder builder = new StringBuilder();
  
  for(int i=1; i<until; i++){
   builder.append(n).append("*").append(i).append("=").append(n*i).append("\n");
  }
  
  return builder.toString();
 }
 
 public static String get2MultiplicationTable(){
  return getMultiplictionTable(2, 10);
 }
}

MultiplicationTableApp.java
package com.sample.demos;

import static javafx.geometry.Pos.CENTER;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class MultiplicationTableApp extends Application {

 @Override
 public void start(Stage primaryStage) {

  Button button = new Button();
  button.setText("Click Me to print multiplication table of 2");

  Text message = new Text();

  button.setOnAction(event -> {
   message.setText(NumberUtil.get2MultiplicationTable());
  });

  VBox vBox = new VBox(10, button, message);
  vBox.setAlignment(CENTER);

  Scene scene = new Scene(vBox, 600, 400);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("Hello JavaFX Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(MultiplicationTableApp.class, args);
 }
}

When you ran above application, you can able to see below window.




When you click on the button, user interface will change like below.






Previous                                                 Next                                                 Home

JavaFX application thread

JavaFX program execution done by JavaFX application thread and not by the main thread. We can confirm the same using below application.

HelloWorld.java
package com.sample.demos;

import static javafx.geometry.Pos.CENTER;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class HelloWorld extends Application {
 @Override
 public void start(Stage primaryStage) {

  String threadName = Thread.currentThread().getName();

  Button button = new Button();
  button.setText("Click Me to know thread details");

  Text message = new Text();

  button.setOnAction(event -> {
   message.setText("Application is getting executed by : " + threadName);
  });

  VBox vBox = new VBox(10, button, message);
  vBox.setAlignment(CENTER);

  Scene scene = new Scene(vBox, 600, 400);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("Hello JavaFX Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(HelloWorld.class, args);
 }
}

When you ran above application, you can able to see below window.


Click on the button to see the thread executing this application.



As you observe above window, the application is getting executed by ‘JavaFX Application Thread’.


Previous                                                 Next                                                 Home

Monday, 7 May 2018

JavaFX: Hello World Application

By extending the abstract class 'javafx.application.Application', you can create a JavaFX application. Your JavaFX application must override the start method of Application class.

Find the below example.

HelloWorld.java
package com.sample.demos;

import static javafx.geometry.Pos.CENTER;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class HelloWorld extends Application {
 @Override
 public void start(Stage primaryStage) {

  Button button = new Button();
  button.setText("Click Me");

  Text message = new Text();

  button.setOnAction(event -> {
   message.setText("Hello World!!!!");
  });

  VBox vBox = new VBox(10, button, message);
  vBox.setAlignment(CENTER);

  Scene scene = new Scene(vBox, 300, 300);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("Hello JavaFX Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(HelloWorld.class, args);
 }
}

When you ran above application, you can able to see below window.
Click on the button ‘Click Me’, you can able to see “Hello World!!!!” message.


How it works
Application class is the entry point for all the JavaFX applications. Main class of JavaFX application extends Application class and must provide implementation of 'start' method. 'start' method is the execution entry point for all the JavaFX applications.

When the application is launched, JavaFx application goes through below life cycle.
a. Initialize the instance of specific Application class.
b. Calls the init() method of the application.
c. Calls the start method
d. Wait until the application finishes.
e. Calls the stop method.

let’s analyze each class of HelloWorld application.

Stage and Scene classes
By using Stage and Scene classes we can define user interface container. Stage is the top-level JavaFX container, whereas Scene is the container for all content. Platform constructs the primary stage. Application can construct additional stages.

You can visualise above application like below.


Button button = new Button();
button.setText("Click Me");
Above statements construct a Button instance with text 'Click Me', it defines a node to display button widget.

Text message = new Text();
Above statement construct a Text object, it defines a node to display text.

button.setOnAction(event -> {
         message.setText("Hello World!!!!");
});
Whenever you click on the button, it set the value "Hello World!!!!" to message Text widget. I written this code using lambda expressions. If you would like to know the lambda expressions, I would recommend you to go through my post.

VBox vBox = new VBox(10, button, message);
vBox.setAlignment(CENTER);
VBox class lays out the children in single vertical column. Above statement creates an VBox layout with the horizantal spacing 10, between children (button and message)

Scene scene = new Scene(vBox, 300, 300);
It is the container for all content in a scene graph. By using scene, we can represent all the visual elements of the user interface. A single element in a scene graph is called node.

primaryStage.setTitle("Hello JavaFX Example");
primaryStage.setScene(scene);
primaryStage.show();
Above statements set the title of primaryStage, set the scene and display the stage.



Previous                                                 Next                                                 Home

Sunday, 6 May 2018

Introduction to JavaFX

JavaFX is a high performance graphical user interface library provided by java. It is used to build platform independent, rich UI client applications.

Why should I use JavaFX?
a.   By using JavaFX, you can develop application across many types of devices (Ex: tablets, desktops, mobile devices etc.,).
b.   JavaFX supports style sheets (css), by using these you can decouple the functional logic from presentation.
c.    By using ‘JavaFX Scene Builder’, you can design user interface without writing single line of code.
d.   JavaFX uses, xml based markup language FXML to construct user interfaces. You can easily port this xml application from one platform to other, you can even change the look and feel of the javaFX application, by changing this FXML file.
e.   You can embed webpages in JavaFX application. JavaScript running in WebView can call Java APIs, and Java APIs can call JavaScript running in WebView.
f.    javaFX support most of the HTML5 features like web socket, web workers, printing capabilities etc.,
g.   You can embed swing content by using SwingNode class of JavaFX.
h.   3D graphic support available
i.     Support Hi-DPI displays.
j.    Provides multi-touch support depending on underlying platform

Prerequisite
You should be comfortable with java basics.

Requirement
a.   Install Jdk1.8 or higher version. If you do not know, how to setup java in your computer, you can go through my below post.




Previous                                                 Next                                                 Home