I'm trying to create a fileChooser within an fxml file. My code looks like this:
<HBox alignment="CENTER">
<Label text="Tower 1 Image" />
<TextField fx:id="tower1ImageField" />
<FileChooser fx:id ="tower1FileChooser" />
</HBox>
And the controller reads like this:
public class HudBuilderController{
@FXML TextField tower1ImageField;
@FXML FileChooser tower1FileChooser;
File towerFile;
@FXML TextField tower2ImageField;
@FXML FileChooser tower2FileChooser;
}
However, I'm getting an error that I don't understand:
Caused by: java.lang.IllegalArgumentException: Unable to coerce javafx.stage.FileChooser@5e85f35 to class javafx.scene.Node.
at com.sun.javafx.fxml.BeanAdapter.coerce(Unknown Source)
at javafx.fxml.FXMLLoader$Element.add(Unknown Source)
at javafx.fxml.FXMLLoader$ValueElement.processEndElement(Unknown Source)
at javafx.fxml.FXMLLoader.processEndElement(Unknown Source)
... 26 more
I've tried instantiating the FileChooser within the controller but I think I need to add more to the fxml file. Any help? Thanks!
The FileChooser
doesnt extend from Node
, therefore you cant use it in your FXML
. Dont forget that the FXML is just a representation of your user interface. There is no need to add all components which you want to use in your Controller to the FXML
.
You only need to initialize a FileChooser
in your controller:
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(extFilter);
File file = fileChooser.showOpenDialog(primaryStage);
System.out.println(file);
JavaFX 8 API Reference: FileChooser
In the end the FileChooser
is a dialog which opens on your screen. Not sure why you want to have it in your FXML? Just use it in your code and work with the filepath you get.
The default property of HBox is children
, which is a list of nodes. Since FileChooser is not a Node, you cannot add it to the children node list of HBox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With