javafx - 在 FXML 中创建 FileChooser

标签 javafx fxml

我正在尝试在 fxml 文件中创建一个 fileChooser。我的代码如下所示:

<HBox alignment="CENTER">
            <Label text="Tower 1 Image" />
            <TextField fx:id="tower1ImageField" />
            <FileChooser fx:id ="tower1FileChooser" /> 
</HBox>

Controller 是这样写的:
public class HudBuilderController{
    @FXML TextField tower1ImageField;
    @FXML FileChooser tower1FileChooser;
    File towerFile; 
    @FXML TextField tower2ImageField;
    @FXML FileChooser tower2FileChooser;
}

但是,我收到一个我不明白的错误:
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

我已经尝试在 Controller 中实例化 FileChooser,但我认为我需要向 fxml 文件添加更多内容。有什么帮助吗?谢谢!

最佳答案

FileChooser不从 Node 扩展,因此您不能在 FXML 中使用它.不要忘记 FXML 只是您的用户界面的表示。无需将要在 Controller 中使用的所有组件添加到 FXML .

你只需要初始化一个 FileChooser在您的 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

到底FileChooser是一个在屏幕上打开的对话框。不确定为什么要在 FXML 中使用它?只需在您的代码中使用它并使用您获得的文件路径。

关于javafx - 在 FXML 中创建 FileChooser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29338352/

相关文章:

java - 从另一个包中获取值(value)

java - JavaFX ListView 中的 WPF ListView.ItemTemplate 等效项是什么?

JavaFX:为节点创建自定义数据属性

java - fxml - 从属性读取值

java - 如何在 JavaFX (fxml) 中制作一个环

java - 更新属性是否需要在主线程上进行?

java - 有没有办法在 JavaFX Webview 中指定用户代理样式表?

java - 如何在 JavaFX 中传递参数

JavaFX - 如何让 VBox 子级与 VBox 父级一起成长

java - 从相应的列标题节点获取 javafx TableColumn