如何在 JavaFX 中为文本添加描边和颜色?

javaobject oriented programmingprogramming更新于 2025/10/12 8:44:17

由于 JavaFX 中的 javafx.scene.text.Text 类继承了 Shape 类,因此它继承了 Shape 类的所有成员。您可以通过将值设置为 Text 类继承的描边、描边宽度和填充属性来修改文本节点的描边和颜色。

  • 描边宽度 − 描边宽度属性指定/定义形状边界线的宽度。您可以使用 Shape 类的 setWidth() 方法将值设置为边界的宽度。

  • 填充 − 填充属性指定/定义要填充形状内部区域的颜色。您可以使用 Shape 类的 fill() 方法用所需的颜色填充特定形状。

  • Stroke − stroke 属性指定/定义形状边界的颜色。您可以使用 javafx.scene.shape.Shape 类的 setStroke() 方法设置边界的颜色。

示例

import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
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 SettingStroke_Color 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);
      //设置舞台
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 150, Color.BEIGE);
      stage.setTitle("Stroke And Color");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

输出


相关文章


有用资源