我制作一个圆圈并使用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();
}
}
如何将其更改为用户想要的位置并从旧位置转到新位置?
谢谢!
答案 0 :(得分:1)
translateX
和centerX
是两个独立的属性,它们都会影响绘制圆的位置。如果您调整其中一个属性,则必须使用相同属性的先前值而不是其他属性。
(类似于y属性。)
您应该将事件处理程序的代码更改为以下内容:
// using only the translate properties
double newY = circle.getTranslateY();
System.out.println("Went to the left.");
double newX = circle.getTranslateX() - 10;
circle.setTranslateX(newX);
circle.setTranslateY(newY);
或
// using only the center properties
double newY = circle.getCenterY();
System.out.println("Went to the left.");
double newX = circle.getCenterX() - 10;
circle.setCenterX(newX);
circle.setCenterY(newY);
注意:代码中不需要与y坐标相关的任何内容,因为这些属性未被修改...