How to add a drop shadow effect to a text node in JavaFX?

Object Oriented ProgrammingProgrammingJavaFX

You can add an effect to any node object in JavaFX using the setEffect() method. This method accepts an object of the Effect class and adds it to the current node.

javafx.scene.effect.DropShadow class represents a drop shadow effect. This effect renders the shadow of the given content behind it, with the specified parameters (color, offset, radius).

Therefore, to add a drop shadow effect to a text node −

  • Instantiate the Text class bypassing basic the x,y coordinates (position), and text string as arguments to the constructor.

  • Set desired properties like font, stoke, etc..

  • Create the drop shadow effect by instantiating the DropShadow class.

  • Set the created effect to the text node using the setEffect() method.

  • Finally, add the created text node to the Group object.

Example

import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.effect.DropShadow;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class DropShadowEffectExample extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Creating a text object
      String str = "Welcome to Tutorialspoint";
      Text text = new Text(30.0, 80.0, str);
      //Setting the font
      Font font = Font.font("Brush Script MT", FontWeight.BOLD, FontPosture.REGULAR, 65);
      text.setFont(font);
      //Setting the color of the text
      text.setFill(Color.BROWN);
      //Setting the width and color of the stroke
      text.setStrokeWidth(2);
      text.setStroke(Color.BLUE);
      //Setting the deep shadow effect to the text
      DropShadow shadow = new DropShadow();
      text.setEffect(shadow);
      //Setting the stage
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 150, Color.BEIGE);
      stage.setTitle("Drop Shadow Effect");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

raja
Published on 16-May-2020 05:52:14
Advertisements