我一直在尝试编写一个程序,能够显示一个圆圈,并允许您使用按钮移动它,但我没能弄清楚如何告诉Java在按下某个按钮时移动圆圈的方向。我已经尝试过setX和setY,但显然它们不是Circle的本地功能。以下是我目前的代码:
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class Ball extends Application {
private Circle circle = new Circle();
@Override
public void start(Stage primaryStage) {
HBox pane = new HBox();
pane.setSpacing(10);
pane.setAlignment(Pos.CENTER);
Button btUp = new Button("UP");
Button btDown = new Button("DOWN");
Button btLeft = new Button("LEFT");
Button btRight = new Button("RIGHT");
pane.getChildren().add(btUp);
pane.getChildren().add(btDown);
pane.getChildren().add(btRight);
pane.getChildren().add(btLeft);
btUp.setOnAction(e -> circle.setY(circle.getY() - 10));
btDown.setOnAction(e -> circle.setY(circle.getY() + 10));
btLeft.setOnAction(e -> circle.setX(circle.getX() - 10));
btRight.setOnAction(e -> circle.setX(circle.getX() + 10));
BorderPane borderPane = new BorderPane();
borderPane.setCenter(circle);
borderPane.setBottom(pane);
BorderPane.setAlignment(pane, Pos.CENTER);
Scene scene = new Scene(borderPane, 200, 200);
primaryStage.setTitle("Ball"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show();
circle.requestFocus();
}
public static void main(String[] args) {
launch(args);
}
}