How do I open the JavaFX FileChooser from a controller class?

扶醉桌前 提交于 2019-12-17 09:40:12

问题


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.

@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?


回答1:


For any node in your scene (for example, the root node; but any node you have injected with @FXML will do), do

chooser.showOpenDialog(node.getScene().getWindow());



回答2:


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.




回答3:


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());

}



回答4:


Alternatively, what worked for me: simply put null.

@FXML
private void onClick(ActionEvent event) {
    File file = fileChooser.showOpenDialog(null);
    if (file != null) {
       //TODO
    }
}


来源:https://stackoverflow.com/questions/25491732/how-do-i-open-the-javafx-filechooser-from-a-controller-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!