我正在使用JavaFX构建绘图程序。我试图使用GraphicsContext绘制一个Rectangle并设法让它在画布上绘制。但是,无论我在哪里点击,它总是从原点开始。当我松开鼠标时(这已经正确完成),矩形停止被绘制,但是当我按下鼠标时,它不会被绘制。这是我的代码:
public RectController(Canvas c, Scene s, BorderPane borderPane){
this.borderPane = borderPane;
this.scene = scene;
this.graphicsContext = canvas.getGraphicsContext2D();
rectangle = new Rectangle();
rectangle.setStrokeWidth(1.0);
rectangle.setManaged(true);
rectangle.setMouseTransparent(true);
//when you first press down on the mouse
pressMouse = event -> {
// borderPane.getChildren().add(rectangle); --> REMOVED
double startX = event.getX();
double startY = event.getY();
};
releaseMouse = event -> {
borderPane.getChildren().remove(rectangle);
double width = Math.abs(event.getX() - startX);
double height = Math.abs(event.getY() - startY);
graphicsContext.strokeRect(startX, startY, width, height);
borderPane.setOnMousePressed(null);
borderPane.setOnMouseDragged(null);
borderPane.setOnMouseReleased(null);
};
dragMouse = event -> {
rectangle.setWidth(event.getX());
rectangle.setHeight(event.getY());
};
}
非常感谢任何帮助。
答案 0 :(得分:0)
这接近你的要求吗?
@FXML AnchorPane apMain;
Rectangle rectangle;
@Override
public void initialize(URL url, ResourceBundle rb) {
}
@FXML void handleOnMouseClick(MouseEvent event)
{
double x = event.getSceneX();
double y = event.getSceneY();
rectangle = new Rectangle();
rectangle.setX(x);
rectangle.setY(y);
rectangle.setWidth(25);
rectangle.setHeight(25);
apMain.getChildren().add(rectangle);
}
@FXML void handleOnMouseDrag(MouseEvent event)
{
rectangle.setWidth(event.getSceneX() - x);
rectangle.setHeight(event.getSceneY() - y);
}
@FXML void handleOnMouseRelease(MouseEvent event)
{
apMain.getChildren().remove(rectangle);
}
你需要做这件事。这是原油。