javafx - 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 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
推荐阅读
- ckeditor - 配置 CKEditor pasteFilter 以去除某些内联样式
- php - 将第二个 url 链接到与不同 url 相同的目录,而不将内容复制到第二个目录?
- javascript - 如何将 Array 转换为 ES6 新的 Map 类型?
- android - 从后台启动混合 Android 应用程序时 HTTP 调用中的奇怪行为
- ios - 昵称的 UITextField
- actions-on-google - 在用户提供输入之前,Google 新 SignIn() 上的操作正在取消
- ruby-on-rails - Unicorn fcntl: Errno::EPERM: Operation not allowed
- azure - 如何修复在 Azure 中创建虚拟网关时地址重叠的错误
- python - 使用 Docker 部署 Django 频道
- r - 计算有条件的元素组合