我正在尝试使用 JavaFX2 中的鼠标事件在图片上绘制矩形。
现在,我在 StackPane 中有一个 ImageView,并在其上添加了 Rectangles。问题是即使我将 Rectangles 的 X 和 Y 设置为 MouseEvent X 和 Y,Rectangles 仍然在 StackPane 中居中。
我想这是默认情况下以每个孩子为中心的 StackPane,但我找不到一个像样的解决方案。你们能指出我正确的方向吗?
这是我的代码:
@FXML
private StackPane stack_pane;
private final ImageView image_view = new ImageView();
private final Set<Rectangle> rectangles = new HashSet<Rectangle>();
private final SimpleDoubleProperty selectionRectInitialX = new SimpleDoubleProperty();
private final SimpleDoubleProperty selectionRectInitialY = new SimpleDoubleProperty();
private final SimpleDoubleProperty selectionRectCurrentX = new SimpleDoubleProperty();
private final SimpleDoubleProperty selectionRectCurrentY = new SimpleDoubleProperty();
private Rectangle selectionRect;
@Override
public void initialize(final URL fxmlFileLocation, final ResourceBundle resources)
{
this.stack_pane.getChildren().add(this.image_view);
this.selectionRect = this.getRectangle();
this.selectionRect.widthProperty().bind(this.selectionRectCurrentX.subtract(this.selectionRectInitialX));
this.selectionRect.heightProperty().bind(this.selectionRectCurrentY.subtract(this.selectionRectInitialY));
this.stack_pane.setOnMousePressed(new EventHandler<MouseEvent>()
{
@Override
public void handle(final MouseEvent event)
{
MainWindowController.this.selectionRect.xProperty().set(event.getX());
MainWindowController.this.selectionRect.yProperty().set(event.getY());
MainWindowController.this.selectionRectInitialX.set(event.getX());
MainWindowController.this.selectionRectInitialY.set(event.getY());
}
});
this.stack_pane.setOnMouseDragged(new EventHandler<MouseEvent>()
{
@Override
public void handle(final MouseEvent event)
{
MainWindowController.this.selectionRectCurrentX.set(event.getX());
MainWindowController.this.selectionRectCurrentY.set(event.getY());
MainWindowController.this.repaint();
}
});
this.stack_pane.setOnMouseReleased(new EventHandler<MouseEvent>()
{
@Override
public void handle(final MouseEvent event)
{
final Rectangle newRect = MainWindowController.this.getRectangle();
newRect.setWidth(MainWindowController.this.selectionRect.getWidth());
newRect.setHeight(MainWindowController.this.selectionRect.getHeight());
newRect.setX(MainWindowController.this.selectionRect.getX());
newRect.setY(MainWindowController.this.selectionRect.getY());
MainWindowController.this.selectionRectCurrentX.set(0);
MainWindowController.this.selectionRectCurrentY.set(0);
MainWindowController.this.rectangles.add(newRect);
MainWindowController.this.repaint();
}
});
}
public Rectangle getRectangle()
{
final Rectangle rect = new Rectangle();
rect.setFill(Color.web("firebrick", 0.4));
rect.setStroke(Color.web("firebrick", 0.4));
return rect;
}
public void repaint()
{
this.stack_pane.getChildren().clear();
this.stack_pane.getChildren().add(this.image_view);
this.stack_pane.getChildren().add(this.selectionRect);
for (final Rectangle rect : this.rectangles)
{
this.stack_pane.getChildren().add(rect);
}
}