При использовании .contains для фигур в JavaFx я получаю разные результаты в зависимости от того, является ли фигура частью группы.
Например, я создаю круг и обводю его, используя графический контекст.Если затем я проверю нажатие мыши на метод содержимого круга, он работает, как и ожидалось.Если я затем добавлю круг в ту же группу, что и холст, и нажму внутри круга, он больше не будет сообщать о каких-либо попаданиях в круг.Так что в основном кажется, что содержит работает, только если круг не является частью группы.
Я пробовал это с другими формами и получаю такое же основное поведение.Я пытался использовать события screenX и screenY, но они также не работают.
protected final VBox vBox;
protected final Button button;
protected final Canvas canvas;
private final Circle circle;
private boolean grouped;
private final Group group;
private Scene scene;
public ContainsTestBase() {
vBox = new VBox();
button = new Button();
canvas = new Canvas();
group = new Group();
setId("AnchorPane");
setPrefHeight(400.0);
setPrefWidth(600.0);
AnchorPane.setBottomAnchor(vBox, 0.0);
AnchorPane.setLeftAnchor(vBox, 0.0);
AnchorPane.setRightAnchor(vBox, 0.0);
AnchorPane.setTopAnchor(vBox, 0.0);
vBox.setLayoutX(228.0);
vBox.setLayoutY(75.0);
vBox.setPrefHeight(400.0);
vBox.setPrefWidth(600.0);
button.setMnemonicParsing(false);
button.setOnAction(this::onTestClicked);
button.setText("Test");
canvas.setHeight(375.0);
canvas.setWidth(600.0);
group.getChildren().add(canvas);
vBox.getChildren().add(button);
vBox.getChildren().add(group);
getChildren().add(vBox);
circle = new Circle(250,250,25);
circle.setFill(Color.AQUA);
drawCircle();
canvas.setOnMousePressed((e)->mouseClicked(e));
}
protected void onTestClicked(javafx.event.ActionEvent actionEvent)
{
if(grouped)
{
group.getChildren().remove(circle);
grouped = false;
}
else
{
group.getChildren().add(circle);
grouped = true;
}
canvas.requestFocus();
}
private void drawCircle()
{
canvas.getGraphicsContext2D().setStroke(Color.BLACK);
canvas.getGraphicsContext2D().strokeOval(circle.getCenterX() - circle.getRadius(), circle.getCenterY() - circle.getRadius(), circle.getRadius() * 2, circle.getRadius() * 2);
}
private void mouseClicked(MouseEvent e)
{
//Note I have also tried sceneX and sceneY with each of these
//options and in each case if the circle was part of a group the
// contains method failed
//works only if circle is not part of group
if (circle.contains(e.getX(), e.getY()))
{
System.out.print("Mouse clicked in circle\n");
}
//works only if circle is not part of group- same results as above
if (circle.getBoundsInParent().contains(e.getX(), e.getY()))
{
System.out.print("Mouse clicked in circle\n");
}
//works only if circle is not part of group- same results as above
if (circle.getBoundsInLocal().contains(e.getX(), e.getY()))
{
System.out.print("Mouse clicked in circle\n");
}
}