你的答案中有几个问题。首先,你检查边界的方式。如果满足该条件,您的钥匙将不再控制
ImageView
. 其次,使用
dice.getX()
dice.getLayoutBounds().getMaxX()
和
dice.getLayoutBounds().getMinX()
scene.getWidth()
Scene
场景
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavaFxTestingGround extends Application {
double KEYBOARD_MOVEMENT_DELTA = 5;
@Override
public void start(Stage primaryStage) throws IOException {
Pane root = new Pane();
Scene scene = new Scene(root, 500, 500, Color.RED);
ImageView dice = new ImageView(createImage("https://cdn.discordapp.com/attachments/250163910454280192/296377451599364107/Untitled.png"));
dice.setFitHeight(100);
dice.setFitWidth(100);
dice.setX(0);
dice.setY(300);
root.getChildren().add(dice);
scene.setOnKeyPressed(e -> {
System.out.println(dice.getLayoutBounds().getMinX() + " : " + dice.getLayoutBounds().getMaxX() + " : " + scene.getWidth());
switch (e.getCode()) {
case RIGHT:
dice.setX(dice.getX() + KEYBOARD_MOVEMENT_DELTA);
break;
case LEFT:
dice.setX(dice.getX() - KEYBOARD_MOVEMENT_DELTA);
break;
}
if (dice.getLayoutBounds().getMinX() < 0)
{
dice.setX(0);
}
else if(dice.getLayoutBounds().getMaxX() > scene.getWidth() )
{
dice.setX(dice.getX() - KEYBOARD_MOVEMENT_DELTA);
}
});
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
Image createImage(String url)
throws IOException {
URLConnection conn = new URL(url).openConnection();
conn.setRequestProperty("User-Agent", "Wget/1.13.4 (linux-gnu)");
try (InputStream stream = conn.getInputStream()) {
return new Image(stream);
}
}
}