code_junkie

How to browse for a file in java swing library?

Nov 12th, 2011
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. final JFileChooser fc = new JFileChooser();
  2. fc.showOpenDialog(this);
  3.  
  4. try {
  5. // Open an input stream
  6. Scanner reader = new Scanner(fc.getSelectedFile());
  7. }
  8.  
  9. String filename = File.separator+"tmp";
  10. JFileChooser fc = new JFileChooser(new File(filename));
  11.  
  12. // Show open dialog; this method does not return until the dialog is closed
  13. fc.showOpenDialog(frame);
  14. File selFile = fc.getSelectedFile();
  15.  
  16. // Show save dialog; this method does not return until the dialog is closed
  17. fc.showSaveDialog(frame);
  18. selFile = fc.getSelectedFile();
  19.  
  20. // This action creates and shows a modal open-file dialog.
  21. public class OpenFileAction extends AbstractAction {
  22. JFrame frame;
  23. JFileChooser chooser;
  24.  
  25. OpenFileAction(JFrame frame, JFileChooser chooser) {
  26. super("Open...");
  27. this.chooser = chooser;
  28. this.frame = frame;
  29. }
  30.  
  31. public void actionPerformed(ActionEvent evt) {
  32. // Show dialog; this method does not return until dialog is closed
  33. chooser.showOpenDialog(frame);
  34.  
  35. // Get the selected file
  36. File file = chooser.getSelectedFile();
  37. }
  38. };
  39.  
  40. // This action creates and shows a modal save-file dialog.
  41. public class SaveFileAction extends AbstractAction {
  42. JFileChooser chooser;
  43. JFrame frame;
  44.  
  45. SaveFileAction(JFrame frame, JFileChooser chooser) {
  46. super("Save As...");
  47. this.chooser = chooser;
  48. this.frame = frame;
  49. }
  50.  
  51. public void actionPerformed(ActionEvent evt) {
  52. // Show dialog; this method does not return until dialog is closed
  53. chooser.showSaveDialog(frame);
  54.  
  55. // Get the selected file
  56. File file = chooser.getSelectedFile();
  57. }
  58. };
Add Comment
Please, Sign In to add comment