Javafx - 光标相交形状

时间:2014-01-07 16:08:48

标签: object javafx mouseevent shape intersect

我在电路板上有几个对象,我想通过坐标获取这些对象的索引。 我尝试使用MouseEvent处理程序并使用getBoundInParent()MouseInfo.getPointerInfo().getLocation()结合使用,但未成功。这些方法给了我不同的坐标,无法与之匹配。

我应该用光标的坐标制作一个矩形并使用getBoundInParent().intersects方法吗?

有任何建议吗?

1 个答案:

答案 0 :(得分:2)

<强>解决方案

在每个形状上,提供setOnMouseEnteredsetOnMouseExited处理程序以捕获鼠标进入和退出事件并记录鼠标所在的形状的索引。

<强>假设

我假设您需要交叉光标热点(例如鼠标指针箭头的尖端)而不是光标形状或光标的矩形边界(因为热点的交叉点是光标工作的标准方式)。

示例应用程序输出

mouseover

  • 当您将鼠标悬停在圆圈上时,圆圈将突出显示并显示圆圈的索引(1)
  • 当您将鼠标悬停在矩形上时,矩形将突出显示,并显示矩形的索引(2)。
  • 如果不将鼠标悬停在任何一种形状上,则两种形状都不会突出显示,也不会显示任何索引。

示例代码

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.stage.Stage;

public class ShapeIntersector extends Application {
    private static final Shape[] shapes = {
            new Circle(50, Color.AQUAMARINE),
            new Rectangle(100, 100, Color.PALEGREEN)
    };

    private static final DropShadow highlight =
            new DropShadow(20, Color.GOLDENROD);

    @Override
    public void start(Stage stage) throws Exception {
        HBox layout = new HBox(40);
        layout.setPadding(new Insets(30));
        layout.setAlignment(Pos.CENTER);

        Label highlightedShapeLabel = new Label(" ");
        highlightedShapeLabel.setStyle(
                "-fx-font-family: monospace; -fx-font-size: 80px; -fx-text-fill: olive"
        );

        for (Shape shape: shapes) {
            layout.getChildren().add(shape);

            shape.setOnMouseEntered(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    shape.setEffect(highlight);
                    int idx = layout.getChildren().indexOf(shape) + 1;
                    highlightedShapeLabel.setText(
                            "" + idx
                    );
                }
            });

            shape.setOnMouseExited(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    shape.setEffect(null);
                    highlightedShapeLabel.setText(" ");
                }
            });
        }

        layout.getChildren().add(highlightedShapeLabel);

        stage.setScene(new Scene(layout));
        stage.show();
    }

    public static void main(String[] args) { launch(args); }
}