8

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!

0

2 Answers 2

9

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.

2
  • 2
    Thanks! I think what I need is instead a button that, on press, opens a file chooser!
    – thb7
    Commented Mar 30, 2015 at 13:51
  • @NDY In line "File file = fileChooser.showOpenDialog(primaryStage);" how do I pass the primaryStage reference into the controller? Commented Dec 20, 2021 at 2:36
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.