这是我的以下代码:
public void start(Stage primaryStage) throws Exception {
Pane root = new Pane();
Scene scene = new Scene(root, 500, 500, Color.WHITE);
ImageView image = new ImageView(new Image(getClass().getResourceAsStream("dice.jpeg")));
image.setX(35);
image.setY(225);
image.setFitWidth(50);
image.setFitHeight(70);
root.getChildren().add(image);
Line line = new Line(20, 40, 120, 40);
line.setStroke(Color.RED);
line.setStrokeWidth(10);
root.getChildren().add(line);
if (line.getBoundsInParent().intersects(image.getBoundsInParent())) {
System.out.println("intersect");
}
Timeline timeline = new Timeline(
new KeyFrame(
Duration.seconds(2),
new KeyValue(line.translateYProperty(), 600)
));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.setAutoReverse(false);
timeline.play();
primaryStage.setScene(scene);
primaryStage.show();
}
我希望在行和图像相交时打印此System.out.println("intersect")
消息,但是当我运行代码时,它不起作用。谁能告诉我我在做什么错?任何帮助都将不胜感激!
我提出了解决方案。这涉及使用线程在其他代码仍在运行时一直检查。代码中的错误是仅在动画开始运行时仅检查一次。
显然,我的代码不是完美的,因此您可能需要清理以适应您的需求:
public class Test extends Application{
public static void main(String[] args) {
Test.launch(args);
//The thread which checks continues to run so you have to stop it
//(There is definitly a better way to do this)
System.exit(0);
}
@Override
public void start(Stage primaryStage) throws Exception {
Pane root = new Pane();
Scene scene = new Scene(root, 500, 500, Color.WHITE);
ImageView image = new ImageView(new Image(getClass().getResourceAsStream("dice.jpeg")));
image.setX(35);
image.setY(225);
image.setFitWidth(50);
image.setFitHeight(70);
root.getChildren().add(image);
Line line = new Line(20, 40, 120, 40);
line.setStroke(Color.RED);
line.setStrokeWidth(10);
root.getChildren().add(line);
//new code
Thread t = new Thread(){
@Override
public void run(){
while(true){
try {
//you could add a Thread.sleep so it only checks every x miliseconds
Thread.sleep(40);
if (line.getBoundsInParent().intersects(image.getBoundsInParent())) {
System.out.println("intersect");
}
} catch (InterruptedException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
t.start();
//end of new code
Timeline timeline = new Timeline(
new KeyFrame(
Duration.seconds(2),
new KeyValue(line.translateYProperty(), 600)
));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.setAutoReverse(false);
timeline.play();
primaryStage.setScene(scene);
primaryStage.show();
}
}