Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create FileChooser in FXML

Tags:

javafx

fxml

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!

like image 374
thb7 Avatar asked Mar 30 '15 04:03

thb7


2 Answers

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.

like image 172
NDY Avatar answered Sep 30 '22 12:09

NDY


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.

like image 41
Puce Avatar answered Sep 30 '22 11:09

Puce