如何在 JavaFX 中向文本节点添加阴影效果?

object oriented programmingprogrammingjavafx更新于 2025/4/14 19:37:17

您可以使用 setEffect() 方法向 JavaFX 中的任何节点对象添加效果。此方法接受 Effect 类的对象并将其添加到当前节点。

javafx.scene.effect.DropShadow 类表示阴影效果。此效果使用指定的参数(颜色、偏移量、半径)在给定内容的后面渲染阴影。

因此,要向文本节点添加阴影效果 −

  • 实例化 Text 类,绕过基本的 x、y 坐标(位置)和文本字符串作为构造函数的参数。

  • 设置所需的属性,如字体、笔触等。

  • 通过实例化 DropShadow类来创建阴影效果。

  • 使用 setEffect()  方法将创建的效果设置为文本节点。

  • 最后,将创建的文本节点添加到 Group 对象。

示例

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 {
      //创建文本对象
      String str = "Welcome to Tutorialspoint";
      Text text = new Text(30.0, 80.0, str);
      //设置字体
      Font font = Font.font("Brush Script MT", FontWeight.BOLD, FontPosture.REGULAR, 65);
      text.setFont(font);
      //设置文本颜色
      text.setFill(Color.BROWN);
      //设置描边的宽度和颜色
      text.setStrokeWidth(2);
      text.setStroke(Color.BLUE);
      //为文本设置深阴影效果
      DropShadow shadow = new DropShadow();
      text.setEffect(shadow);
      //设置舞台
      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);
   }
}

输出


相关文章