问题
I have an application in which I draw a rectangle and then turn it 90 degrees. In this case, I have a frame with which I can move my rectangle. But after I turned it (an example of 90 degrees), when the region moves up, the rectangle itself moves to the right. When rotating, what does the coordinate proxy of the shape itself turn? Rotation code:
this.rotation.addListener((obs, old, fresh) -> {
Rotate rotate = new Rotate((double) fresh - (double) old,
x.getValue().doubleValue() + (width.getValue().doubleValue() / 2),
y.getValue().doubleValue() + (height.getValue().doubleValue() / 2));
shape.getTransforms().add(rotate);
rotate.angleProperty().bind(this.rotation);
});
When you rotate the rectangle, its coordinate axis rotates with it.
How to make it so that when you update the coordinate axis in the initial position?
回答1:
I don't truly understand your question but here is an example that demos rotating and moving a rectangle. Double click the rectangle to rotate it. (Double click is not perfect if clicking too fast.). Drag the rectangle to move it.
import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
public class JavaFXApplication extends Application
{
final ObjectProperty<Point2D> mousePosition = new SimpleObjectProperty<>();
public static void main(String[] args)
{
Application.launch(args);
}
@Override
public void start(Stage primaryStage)
{
Rotate rotate = new Rotate();
Rectangle rectangle = new Rectangle(33, 100, Color.GREEN);
rectangle.setX((1200 / 2) - (33 / 2));
rectangle.setY((900 / 2) - (100 / 2));
rectangle.rotateProperty().bind(rotate.angleProperty());
rectangle.setOnMouseClicked((event) -> {
if (event.getButton().equals(MouseButton.PRIMARY)) {
if (event.getClickCount() == 2) {
System.out.println("Double Clicked!");
rotate.setAngle(rotate.getAngle() + 90);
}
}
});
rectangle.setOnMousePressed((MouseEvent event) -> {
mousePosition.set(new Point2D(event.getSceneX(), event.getSceneY()));
});
rectangle.setOnMouseDragged((MouseEvent event) -> {
double deltaX = event.getSceneX() - mousePosition.get().getX();
double deltaY = event.getSceneY() - mousePosition.get().getY();
rectangle.setLayoutX(rectangle.getLayoutX() + deltaX);
rectangle.setLayoutY(rectangle.getLayoutY() + deltaY);
mousePosition.set(new Point2D(event.getSceneX(), event.getSceneY()));
});
Pane root = new Pane(rectangle);
Scene scene = new Scene(root, 1200, 900, Color.LIGHTGRAY);
primaryStage.setScene(scene);
primaryStage.setTitle("Path Transition Example");
primaryStage.show();
}
}
来源:https://stackoverflow.com/questions/53293315/javafx-rotation