JavaFX文本选择背景 [英] JavaFX Text Selection background
问题描述
可以在 javafx.scene.text.Text
中设置选择区域的填充.
It is possible to set the fill for a selection area in a javafx.scene.text.Text
.
setFill(RED);
但是,似乎没有等效的 setBackground(BLUE)
However, there seems to be no equivalent 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);
}
}
默认情况下,文本选择的填充为白色.将文本设置为白色可能是为了为不同的背景(例如蓝色)做好准备.
By default, the fill for the text selection is white. Having the text white is probably for preparing it for a different background, like blue.
如何为所选文本设置背景?
How to achieve background for selected text?
推荐答案
If you're using JavaFX 9+ then you can use the Text#selectionShape
property:
以局部坐标表示的选择的形状.
The shape of the selection in local coordinates.
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.
这篇关于JavaFX文本选择背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!