0
我有一个TextArea
这在ScrollPane
其中ScrollPane
可以通过在TextArea
调用getParent()
五次找到。有没有办法找到TextArea
相对于ScrollPane
的坐标?获取节点相对于的边界到另一节点/窗格JavaFX的
我有一个TextArea
这在ScrollPane
其中ScrollPane
可以通过在TextArea
调用getParent()
五次找到。有没有办法找到TextArea
相对于ScrollPane
的坐标?获取节点相对于的边界到另一节点/窗格JavaFX的
你可以这样做:
Bounds bounds =
scrollPane.sceneToLocal(textArea.localToScene(textArea.getBoundsInLocal()));
这里有一个完整的例子:
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class TextAreaBoundsInScrollPane extends Application {
@Override
public void start(Stage primaryStage) {
ScrollPane scrollPane = new ScrollPane();
VBox scrollPaneContent = new VBox(5);
TextArea textArea = new TextArea();
scrollPaneContent.setPadding(new Insets(10));
scrollPaneContent.setAlignment(Pos.CENTER);
scrollPaneContent.getChildren().add(new Rectangle(200, 80, Color.CORAL));
scrollPaneContent.getChildren().add(textArea);
scrollPaneContent.getChildren().add(new Rectangle(200, 120, Color.CORNFLOWERBLUE));
scrollPane.setContent(scrollPaneContent);
BorderPane root = new BorderPane(scrollPane);
root.setTop(new TextField());
root.setBottom(new TextField());
ChangeListener<Object> boundsChangeListener = (obs, oldValue, newValue) -> {
Bounds bounds = scrollPane.sceneToLocal(textArea.localToScene(textArea.getBoundsInLocal()));
System.out.printf("[%.1f, %.1f], %.1f x %.1f %n", bounds.getMinX(), bounds.getMinY(), bounds.getWidth(), bounds.getHeight());
};
textArea.boundsInLocalProperty().addListener(boundsChangeListener);
textArea.localToSceneTransformProperty().addListener(boundsChangeListener);
scrollPane.localToSceneTransformProperty().addListener(boundsChangeListener);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
这会不会找到textarea的界限?它似乎并没有为我工作。 – Vasting
是的,它会在滚动窗格的坐标系中给出文本区域的边界。 –
增加了一个SSCCE。 –