我在javafx中有一个TextArea,但我需要获得坐标或位置(x,y)来移动TextArea中的浮动菜单



我有一个问题,无法找到解决方法。我在互联网上搜索了一下,没有找到任何信息告诉我如何用JavaFX获得TextArea中插入符号的坐标或位置(x,y(。

TextInputControl有一个属性cartePosition,它将文本中的位置表示为字符索引。将文本坐标转换为(x,y(坐标的合作者是它的皮肤:TextInputControlSkin提供了一种转换方法getCharacterBounds(index)

因此,跟踪(x,y(坐标中插入符号位置的方法是

  1. 在文本坐标中侦听控件的插入符号位置
  2. 查询其皮肤以将文本坐标转换为二维坐标
  3. 使用这些来定位节点

下面的简单示例在插入符号周围显示了一个红色矩形。

public class TextCaretPosition extends Application  {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("TextArea Experiment 1");
TextArea textArea = new TextArea("This is allnmy textnin here.");
ObjectProperty<Rectangle> caretShape = new SimpleObjectProperty<>();
textArea.caretPositionProperty().addListener((src, ov, nv ) -> {
TextInputControlSkin<TextArea> skin = (TextInputControlSkin<TextArea>) textArea.getSkin();
if (skin != null) {
Rectangle2D bounds = skin.getCharacterBounds(nv.intValue());
caretShape.set(new Rectangle(bounds.getMinX(), bounds.getMinY(), 
bounds.getWidth(), bounds.getHeight()));
}
});
caretShape.addListener((src, ov, r) -> {
Skin<?> skin = textArea.getSkin();
if (skin instanceof SkinBase) {
if (ov != null) {
((SkinBase<?>) skin).getChildren().remove(ov);
} 
if (r != null) {
r.setStroke(Color.RED);
r.setFill(Color.TRANSPARENT);
r.setMouseTransparent(true);
((SkinBase<?>) skin).getChildren().add(r);
}
}
});
VBox vbox = new VBox(textArea);
Scene scene = new Scene(vbox, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

最新更新