我们想要创建一个应用程序,用户可以在场景中制作不同的多边形,然后程序允许用户通过单击它们来识别这些多边形。多边形是在代码的这一部分中制作的:
private boolean draw = true;
private Polugon polygon;
private Group root;
private List<Double> coordinates = new ArrayList<>();
int polygonId = 0;
private EventHandler<MouseEvent> polygonDrawer = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getClickCount() == 2 && draw) { //if the user clicks on the scene twice the polygon-drawing is finished
draw = false;
polygonId ++; //every polygon has its own ID
coordinates = new ArrayList<>();
} else if (mouseEvent.getEventType() == MouseEvent.MOUSE_PRESSED) {
draw = true;
coordinates.add(mouseEvent.getX());
coordinates.add(mouseEvent.getY());
polygon = new Polugon(polygonId);
polygon.getPoints().addAll(coordinates);
root.getChildren().add(polygon);
}
}
};
Class Polugon:
public class Polugon extends Polygon{
private int id;
public Polugon(int id) {
this.id = id;
}
public String toString() {
return "Polygon ID " + id;
}
//there are other methods
}
我们尝试制作一个EventHandler,它会在单击多边形时打印出多边形的ID,但它总是返回已绘制的最后一个多边形的ID。有关详细信息:我们有ToggleButtons用于绘制多边形并获取场景中多边形的ID。
如果这些多边形具有相同的变量名称,如何识别这些多边形?