在JavaFx中将.contains用于形状时,根据形状是否为组的一部分,会得到不同的结果。
例如,我创建一个圆,然后使用图形上下文对其进行描边。如果然后我检查鼠标是否按圆圈的contains方法,它将按预期工作。如果再将圈子与画布添加到同一组,然后在圈子内单击,它将不再报告圈子内的任何点击。因此,基本上,只有在圈子不属于组的情况下,似乎包含才起作用。
我用其他形状尝试了此操作,并获得了相同的基本行为。我曾尝试使用事件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");
}
}