我正在尝试在fxml文件中创建一个fileChooser。我的代码如下所示:
<HBox alignment="CENTER">
<Label text="Tower 1 Image" />
<TextField fx:id="tower1ImageField" />
<FileChooser fx:id ="tower1FileChooser" />
</HBox>控制器读起来像这样:
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我已经尝试在控制器中实例化FileChooser,但我认为需要向fxml文件添加更多内容。有什么帮助吗?谢谢!
发布于 2015-03-30 14:18:09
FileChooser不是从Node扩展而来的,因此你不能在FXML中使用它。不要忘记,FXML只是用户界面的一种表示形式。不需要将要在控制器中使用的所有组件添加到FXML中。
您只需要在控制器中初始化一个FileChooser:
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中包含它?只需在您的代码中使用它,并使用您获得的文件路径。
发布于 2015-03-30 19:41:02
HBox的默认属性是children,它是一个节点列表。由于FileChooser不是节点,因此无法将其添加到HBox的子节点列表中。
https://stackoverflow.com/questions/29338352
复制相似问题