Cho đến nay tôi đã mã hóa một ứng dụng JavaFX trong đó một số hình chữ nhật di chuyển xung quanh. Bây giờ tôi muốn tạo ra một phương pháp để kiểm tra xem một hình chữ nhật vẫn còn nhìn thấy trong cửa sổ hoặc đã được di chuyển ra khỏi nó. Mã của tôi trông như thế:Cách kiểm tra xem nút hình chữ nhật có nằm trong cửa sổ
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);
}
}
Phương pháp outOfWindow()
là nỗ lực của tôi để kiểm tra xem vị trí của hình chữ nhật vẫn đang trong cửa sổ. Nó hoạt động. Nhưng có cách nào tốt hơn hay cách nào để phát hiện đường viền cửa sổ hình chữ nhật nào bị gạch chéo?
Điều này có thể giúp bạn ra ngoài - Mặc dù tập trung vào 'ScrollPane' hơn: https://stackoverflow.com/questions/28701208/javafx-ask-wether-a-node-is-inside -xuất khẩu hay không – Chris