I have a quite strange problem in javafx. If I add some rectangles to a anchorpane and delete them afterwards, I get the following exception:
java.lang.IllegalArgumentException: Children: duplicate children added: parent = AnchorPane
But now the real problem shows up: The exception is quite random. So, I do not get the exception always when I delete a rectangle and that is what I do not understand. I already debugged everything, but there are no differences between a "no exception termination" and a "with exception termination" (I hope somebody can understand my weird writing xd) Another problem is that I do not know how to reproduce this issue. It is to 100% my fault, but I cannot say what I am doing wrong.
Now my last try is to ask a question here. Does anybody has some tips for this exception? (I am using the newest IntelliJ version and JDK17 + JavaFX 17)
Rectangle/Node Class:
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.shape.Rectangle;
import java.text.DecimalFormat;
import java.util.Objects;
public class MyNode extends Rectangle {
private int myNodeId;
private SimpleStringProperty myNodeIdProperty;
private DecimalFormat threeDigits;
public MyNode() {
}
public MyNode(double xCord, double yCord, double width, double height, int myNodeId) {
super(xCord, yCord, width, height);
this.myNodeId = myNodeId;
threeDigits = new DecimalFormat("000");
this.myNodeIdProperty = new SimpleStringProperty();
this.myNodeIdProperty.set(threeDigits.format(myNodeId));
}
public int getMyNodeId() {
return myNodeId;
}
public void setMyNodeId(int myNodeId) {
this.myNodeIdProperty.set(threeDigits.format(myNodeId));
this.myNodeId = myNodeId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyNode myNode = (MyNode) o;
return myNodeId == myNode.myNodeId;
}
@Override
public int hashCode() {
return Objects.hash(myNodeId);
}
}
Maybe someone sees already a weird thing in my node class. As you can see, I have a unique id and a property to bind this id to a tableview cell. I add and remove the nodes with the following code:
anchorPane.getChildren().add(myNode);
anchorPane.getChildren().remove(myNode);
I see forward to your answers. Thanks.
The problem was the overrides of the equals and hashcode methods... I removed them and now everything works fine. Thank you @Slaw.