我在电路板上有几个对象,我想通过坐标获取这些对象的索引。
我尝试使用MouseEvent
处理程序并使用getBoundInParent()
与MouseInfo.getPointerInfo().getLocation()
结合使用,但未成功。这些方法给了我不同的坐标,无法与之匹配。
我应该用光标的坐标制作一个矩形并使用getBoundInParent().intersects
方法吗?
有任何建议吗?
答案 0 :(得分:2)
<强>解决方案强>
在每个形状上,提供setOnMouseEntered和setOnMouseExited处理程序以捕获鼠标进入和退出事件并记录鼠标所在的形状的索引。
<强>假设强>
我假设您需要交叉光标热点(例如鼠标指针箭头的尖端)而不是光标形状或光标的矩形边界(因为热点的交叉点是光标工作的标准方式)。
示例应用程序输出
示例代码
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); }
}