A Swing ActionListener that opens a JFileChooser and returns the selected file


/ Published in: Java
Save to your folder(s)

A Swing ActionListener that opens a JFileChooser and returns the selected file.


Copy this code and paste it in your HTML
  1. /** This action creates and shows a modal save-file dialog. */
  2. public abstract static class FileAction extends AbstractAction {
  3.  
  4. private final JFileChooser chooser = new JFileChooser();
  5. private final JPanel parent;
  6.  
  7. FileAction(JPanel parent) {
  8. this.parent = parent;
  9. }
  10.  
  11. @Override public void actionPerformed(ActionEvent evt) {
  12. // Show dialog; won't return until dialog is closed:
  13. chooser.showSaveDialog(parent);
  14.  
  15. // Get the selected file
  16. File file = chooser.getSelectedFile();
  17. if (file != null) {
  18. handleFile(file);
  19. }
  20. }
  21.  
  22. public abstract void handleFile(File file);
  23. }
  24.  
  25. ...
  26.  
  27. myButton.addActionListener(new FileAction(getMainPanel()) {
  28. @Override public void handleFile(File file) {
  29. // do whatever you want with the file...
  30. }
  31. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.