I am trying to create an editable TreeTableView
from a XML Document.
For this, i am wrapping the Elements from the Document within a class.
The Data of the Elements is stored within the attributes key and val.
My Wrapper consists of
private Element node;
private final StringProperty key = new SimpleStringProperty(this, node.getAttribute("key"), "temp");
private final StringProperty val = new SimpleStringProperty(this, node.getAttribute("val"), "temp");
public ElementWrapper(Element n){
System.out.println("creating element "+n.getNodeName());
node = n;
}
public String getKey(){
return key.get();
}
@Override
public String getVal(){
return key.get();
}
public void setKey(String key){
((Element)node).setAttribute("key", key);
}
@Override
public void setVal(String value){
((Element)node).setAttribute("val", value);
}
@Override
public Element getElement(){
return node;
}
@Override
public StringProperty keyProperty(){
return key;
}
@Override
public StringProperty valProperty(){
return val;
}
I wrote a recursive algorithm which creates the tree items and sets them with
TreeItem<NodeWrapper> newsub = new TreeItem<>(new ElementWrapper(current));
where current is the XML Element. At this Point i get a NullPointerException
for
lib.ElementWrapper.<init>(ElementWrapper.java:21)
which is the second line of the Wrapper
class posted above.
How do i set this correctly?
Change it to:
private Element node;
private final StringProperty key;
private final StringProperty val;
public ElementWrapper(Element n){
System.out.println("creating element " + n.getNodeName());
node = n;
key = new SimpleStringProperty(this, node.getAttribute("key"));
val = new SimpleStringProperty(this, node.getAttribute("val"));
}
Because these initializations are done before executing costructor:
private final StringProperty key = new SimpleStringProperty(this, node.getAttribute("key"), "temp");
private final StringProperty val = new SimpleStringProperty(this, node.getAttribute("val"), "temp");
Here is nice question about initialization: Java order of Initialization and Instantiation.
Official documentation: Initializing Fields.