首页 > 解决方案 > JavaFX 文本选择背景

问题描述

可以在 中设置选择区域的填充javafx.scene.text.Text

setFill(RED);

但是,似乎没有等价物setBackground(BLUE)

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Pane p = new Pane();
        Scene s = new Scene(p);
        s.getStylesheets().add("main.css");
        primaryStage.setScene(s);
        primaryStage.show();

        addTextWithSelection(p);
    }

    private void addTextWithSelection(Pane p) {
        Text t = new Text(20,20, "Some Text selection some more text");
        t.setSelectionStart(11);
        t.setSelectionEnd(18);
        t.setSelectionFill(GREEN);
        p.getChildren().add(t);
    }
}

默认情况下,文本选择的填充为白色。将文本设置为白色可能是为了准备它以适应不同的背景,例如蓝色。

如何实现选定文本的背景?

标签: javafx

解决方案


如果您使用的是 JavaFX 9+,那么您可以使用以下Text#selectionShape属性:

局部坐标中选择的形状。

该属性为您提供了 a PathElement[],它可以与 a 一起使用Path以实现选定文本的背景颜色。这是一个概念验证

import javafx.application.Application;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Path;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public final class App extends Application {

  @Override
  public void start(Stage primaryStage) {
    var text = new Text("Some text to demonstrate the selection-shape property.");
    text.setTextOrigin(VPos.TOP);
    text.setFont(Font.font("Monospaced", 24));
    text.setSelectionStart(5);
    text.setSelectionEnd(24);
    text.setSelectionFill(Color.WHITE); // fill of the actual text when selected

    var path = new Path(text.getSelectionShape());
    path.setStrokeWidth(0);
    path.setFill(Color.FORESTGREEN);

    // add 'path' first so it's rendered underneath 'text'
    primaryStage.setScene(new Scene(new Pane(path, text)));
    primaryStage.show();
  }
}

请注意,在实际应用程序中,所选文本可以更改,您希望观察selectionShape属性并Path根据需要进行更新。

另请注意,如文件所述,PathElement[]是在 的局部坐标空间中给出的Text。这意味着如果您希望它们正确对齐,则应用到Text( 不影响其bounds-in-local ) 的任何转换都需要应用到。Path


推荐阅读