[英]How to check if rectangular node is in the window
到目前為止,我已經編寫了一個JavaFX應用程序,其中一些矩形在其中移動。 現在,我想創建一個方法來檢查矩形在窗口中是否仍然可見或已移出矩形。 我的代碼如下所示:
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Test extends Application {
private Pane root = new Pane();
private Rectangle rect = new Rectangle(150,150,15,15);
private Point2D velocity = new Point2D(2,1);
private Pane createContent(){
root.setPrefSize(500,500);
root.getChildren().add(rect);
AnimationTimer timer = new AnimationTimer() {
@Override
public void handle(long now) {
update();
}
};
timer.start();
return root;
}
private void update(){
if (outOfWindow(rect)) {
System.out.println("out of window...\n");
}else {
System.out.println("in window...\n");
}
rect.setTranslateX(rect.getTranslateX() + velocity.getX());
rect.setTranslateY(rect.getTranslateY() + velocity.getY());
}
private boolean outOfWindow(Node node) {
if (node.getBoundsInParent().intersects(node.getBoundsInParent().getWidth(), node.getBoundsInParent().getHeight(),
root.getPrefWidth() - node.getBoundsInParent().getWidth() * 2,
root.getPrefHeight() - node.getBoundsInParent().getHeight() * 2)){
return false;
}
return true;
}
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(createContent()));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
我嘗試用outOfWindow()
方法檢查矩形的位置是否仍在窗口中。 有用。 但是,有沒有更好的方法或一種方法來檢測矩形所穿過的窗口邊界?
如果一個矩形在另一個矩形的外面,則意味着兩件事:
因此,您的方法可以采用以下方式:
private boolean inTheWindow(Rectangle rect) {
return rect.getBoundsInParent().intersects(root.getLayoutBounds())
|| root.getLayoutBounds().contains(rect.getBoundsInParent());
}
這是MCVE演示:
public class FXBounds extends Application {
private Pane root;
@Override
public void start(Stage primaryStage) {
root = new Pane();
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
check(1,1,50,50, true);
check(100,100,50,50, true);
check(-5,-5,30,30, true);
check(-50,0,30,30, false);
}
private void check(int x, int y, int width, int height, boolean in) {
Rectangle rect = new Rectangle(x, y, width, height);
root.getChildren().add(rect);
System.out.println(in == inTheWindow(rect));
}
private boolean inTheWindow(Rectangle rect) {
return rect.getBoundsInParent().intersects(root.getLayoutBounds()) || root.getLayoutBounds().contains(rect.getBoundsInParent());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.