2

I have a custom class that I am using JavaFX FXML loader to create the objects.

I can reproduce me problem with a simple test class with a setter for the count property:

public class MyBlock {
    int count;
    public MyBlock(){

    }
    public void setCount(int i){
        count = i;
    }
}

And the FXML file is:

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import com.mycode.io.base.*?>
<?import com.mycode.io.elements.*?>


<Header fx:id="header"  xmlns:fx="http://javafx.com/fxml/1" >
    <children>
        <MyBlock fx:id="chartWindow" count="5"/>
    </children>
</Header>

When I run the app I get an error pointing to the "MyBlock" line in the FXML.

javafx.fxml.LoadException:

My understanding of the FXMLLoader is that it uses the setter to set the property. It took me a while to work out the the error was caused by me not having a getter for the count property. So by adding the getter code to my class everything works perfectly.

public class MyBlock {
    int count;
    public MyBlock(){

    }
    public void setCount(int i){
        count = i;
    }
    // added getter
    public int getCount(){
        return count;
    }
}

I have reviewed the Java FX 8.0 Introduction to FXML and in the "Property Elements" section they mention you need a setter, but does not mention needing a getter.

My question is two fold. Why does FXMLLoader need getter to use the setter? Is there a way of using the FXML loader without having to write getters for each property.

Mike davison
  • 309
  • 4
  • 17
  • 1. In your example, you set `count` to 5, so FXMLLoader needs the setter to set it, why wouldn't you have a setter? 2. Have you tried declaring `count` public? `public int count;` – Marcelo Li Koga Nov 17 '17 at 10:21
  • 2
    `FXMLLoader` uses the getter to determine the type of the property. You may get around this restriction by using a constructor+`@NamedArg` to initialize the property but I haven't tested this, so I'm not sure. Also `FXMLLoader` does have problems with this kind of initialisation sometimes... – fabian Nov 17 '17 at 11:17
  • Thanks Fabian. Very logical answer. This makes a lot of sense because in FXML all values are entered as quoted text so I can see that the the `FXMLLoader` needs to determine type. I will try `@NamedArg` and see if that helps. – Mike davison Nov 18 '17 at 00:25

0 Answers0