如何从控制器类打开 JavaFX FileChooser?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25491732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I open the JavaFX FileChooser from a controller class?
提问by Electric Coffee
My problem is that all the examples of using FileChooser
requires you to pass in a stage. Only problem is that my UI is defined in an fxml
file, which uses a controller class separate from the main stage.
我的问题是所有使用的例子都FileChooser
需要你通过一个阶段。唯一的问题是我的 UI 是在一个fxml
文件中定义的,该文件使用与主阶段分开的控制器类。
@FXML protected void locateFile(ActionEvent event) {
FileChooser chooser = new FileChooser();
chooser.setTitle("Open File");
chooser.showOpenDialog(???);
}
What do I put at the ???
to make it work? Like I said, I don't have any references to any stages in the controller class, so what do I do?
我在里面放了什么才能???
让它工作?就像我说的,我没有对控制器类中的任何阶段进行任何引用,那我该怎么办?
采纳答案by James_D
For any node in your scene (for example, the root node; but any node you have injected with @FXML
will do), do
对于场景中的任何节点(例如,根节点;但您注入的任何节点都@FXML
可以),请执行
chooser.showOpenDialog(node.getScene().getWindow());
回答by Mansueli
You don't have to stick with the Stage created in the Application you can either:
您不必坚持使用在应用程序中创建的舞台,您可以:
@FXML protected void locateFile(ActionEvent event) {
FileChooser chooser = new FileChooser();
chooser.setTitle("Open File");
File file = chooser.showOpenDialog(new Stage());
}
Or if you want to keep using the same stage then you have to pass the stage to the controller before:
或者,如果您想继续使用同一个舞台,那么您必须先将舞台传递给控制器:
FXMLLoader loader = new FXMLLoader(getClass().getResource("yourFXMLDocument.fxml"));
Parent root = (Parent)loader.load();
MyController myController = loader.getController();
myController.setStage(stage);
and you will have the main stage of the Application there to be used as you please.
您将可以随意使用应用程序的主要阶段。
回答by spinnaker15136
From a menu item
从菜单项
public class SerialDecoderController implements Initializable {
@FXML
private MenuItem fileOpen;
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
public void fileOpen (ActionEvent event) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
fileChooser.showOpenDialog(fileOpen.getParentPopup().getScene().getWindow());
}
回答by luke8800gts
Alternatively, what worked for me: simply put null
.
或者,对我有用的是:简单地将null
.
@FXML
private void onClick(ActionEvent event) {
File file = fileChooser.showOpenDialog(null);
if (file != null) {
//TODO
}
}