且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaFX文本选择背景

更新时间:2023-12-04 12:34:58

如果您使用的是JavaFX 9+,则可以使用

If you're using JavaFX 9+ then you can use the Text#selectionShape property:

以局部坐标表示的选择的形状.

The shape of the selection in local coordinates.

该属性为您提供一个 PathElement [] ,可以与

The property gives you a PathElement[] which can be used with a Path to implement a background color for selected text. Here's a proof-of-concept:

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 .

Note in a real application where the selected text can change you'd want to observe the selectionShape property and update the Path as needed.

还要注意,如所记录的那样, PathElement [] 是在 Text 的局部坐标空间中给出的.这意味着应用于文本的任何转换(不影响其本地边界)都需要应用于 Path 同样,如果您希望它们正确对齐.

Also note that, as documented, the PathElement[] is given in the local coordinate space of the Text. This means any transformations applied to the Text (which don't affect its bounds-in-local) will need to be applied to the Path as well if you want them to align properly.