Posted By

liqweed on 11/18/09


Tagged

java swing


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

kubaitis


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


 / Published in: Java
 

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

  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  

You need to login to post a comment.