我正在尝试在 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/