【发布时间】:2017-07-01 12:48:53
【问题描述】:
到目前为止,我编写了一个 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() 方法是我尝试检查矩形的位置是否仍在窗口中。有用。但是有没有更好的方法或方法来检测矩形越过哪个窗口边界?
【问题讨论】:
-
这可能会对您有所帮助 - 虽然它更专注于
ScrollPane: stackoverflow.com/questions/28701208/…