JavaFX - Smooth Property



Smoothing is a more common process seen in Statistics or Image processing. It is defined as a process in which coordinates or data points are averaged with their neighbouring points of a series, such as a time series, or image. This results in the effect of blurring the sharp edges in the smoothed data. Smoothing is sometimes referred to as filtering, because smoothing has the effect of suppressing high frequency signal and enhancing low frequency signal.

The process of smoothing is done usually to fine scale an image or a data set. In JavaFX, using this property on 2D shapes will fine tune the edges.

Smooth Property

The smooth property in JavaFX is used to smoothen the edges of a certain 2D shape. This property is of the type Boolean. If this value is true, then the edges of the shape will be smooth.

You can set value to this property using the method setSmooth() as follows −

path.setSmooth(false);

By default, the smooth value is true. Following is a diagram of a triangle with both smooth values.

smooth

Example

In the following example, we will try to smoothen the edges of a 2D shape, say a circle. Save this file with the name SmoothExample.java.

import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.shape.Circle;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.paint.Color;
import javafx.stage.Stage;  

public class SmoothExample extends Application { 
   @Override 
   public void start(Stage stage) {        
      //Creating a Circle 
      Circle circle = new Circle(150.0, 150.0, 100.0);  

      circle.setFill(Color.BLUE);
      circle.setStroke(Color.BLACK);
      circle.setStrokeWidth(5.0);
      circle.setSmooth(true);

      //Creating a Group object  
      Group root = new Group(circle);

      //Creating a scene object 
      Scene scene = new Scene(root, 300, 300);  

      //Setting title to the Stage 
      stage.setTitle("Drawing a Circle"); 

      //Adding scene to the stage 
      stage.setScene(scene); 

      //Displaying the contents of the stage 
      stage.show(); 
   } 
   public static void main(String args[]){ 
      launch(args); 
   } 
}

Compile and execute the saved java file from the command prompt using the following commands.

javac --module-path %PATH_TO_FX% --add-modules javafx.controls SmoothExample.java 
java --module-path %PATH_TO_FX% --add-modules javafx.controls SmoothExample

Output

On executing, the above program generates a JavaFX window displaying a circle with smoothened stroke as shown below.

Smooth Output
Advertisements