원을 만들고 4 개의 버튼 (왼쪽, 오른쪽, 위, 아래)으로 움직이는 코드가 작동하지만, 새 위치에서 이동하지 않고 이동합니다. 시작 위치 (y = 0 및 x = 0)부터.원이 새 위치에서 시작 위치로 이동하지 않습니다.
package movetheball;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.geometry.Pos;
public class MoveTheBall extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Circle circle = new Circle();
circle.setRadius(50);
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
Button btn1 = new Button();
btn1.setText("Left");
btn1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
double newY = 0;
double newX = 0;
System.out.println("Went to the left.");
newX = circle.getCenterX() - 10;
circle.setTranslateX(newX);
circle.setTranslateY(newY);
}
});
Button btn2 = new Button();
btn2.setText("Right");
btn2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
double newY = 0;
double newX = 0;
System.out.println("Went to the right.");
newX = circle.getCenterX() + 10;
circle.setTranslateX(newX);
circle.setTranslateY(newY);
}
});
Button btn3 = new Button();
btn3.setText("Up");
btn3.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
double newY = 0;
double newX = 0;
System.out.println("Went up.");
newY = circle.getCenterY() - 10;
circle.setTranslateX(newX);
circle.setTranslateY(newY);
}
});
Button btn4 = new Button();
btn4.setText("Down");
btn4.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
double newY = 0;
double newX = 0;
System.out.println("Went down.");
System.out.println("Went up.");
newY = circle.getCenterY() + 10;
circle.setTranslateX(newX);
circle.setTranslateY(newY);
}
});
BorderPane rootPane = new BorderPane();
rootPane.setCenter(circle);
HBox hb = new HBox(btn1, btn2, btn3, btn4);
hb.setAlignment(Pos.CENTER);
rootPane.setBottom(hb);
Scene scene = new Scene(rootPane, 400, 400);
primaryStage.setTitle("Move the circle!");
primaryStage.setScene(scene);
primaryStage.show();
}
}
어떻게 사용자가 원하는 위치로 이동하고 이전 위치에서 새 위치로 이동합니까?
감사합니다.
청중 내에서 항상 double newY = 0;'('x'와 동일)을 수행합니다. 서클의 x/y 값을 리스너 외부에 저장해야합니다 (예 : 클래스의 멤버 변수 내에서. – pzaenger