Next page | Contents page |

javax.swing.JFileChooser

Simple example of browsing to save a file:

	JFileChooser fc = new JFileChooser ();
	int result = fc.showSaveDialog (g);

	if (result == JFileChooser.APPROVE_OPTION)
	{
		save (fc.getCurrentDirectory (),
				fc.getSelectedFile ());	// a File object
	}

JFileChooser.showOpenDialog (parent) is similar for file opening.

JFileChooser can be tailored considerably. The next example shows some of the possibilities. Within an application you may well want to keep track of the directory chosen, in order to give a sensible default for the next file dialogue.

	JFileChooser fc = new JFileChooser ();
	fc.setCurrentDirectory (new File (
				System.getProperty("user.dir")));
	fc.setFileSelectionMode (JFileChooser.DIRECTORIES_ONLY);
	fc.setDialogType (JFileChooser.OPEN_DIALOG);

	// Can show the dialogue & check the result in one go:
	if (JFileChooser.APPROVE_OPTION ==  
		   fc.showDialog (null, "Set root path"))
	{
		path = fc.getSelectedFile ().getPath ();
		// ...
	}

Set the JFileChooser object to allow multiple files to be selected:

    fc.setMultiSelectionEnabled (true); 

then get them as an array with fc.getSelectedFiles ().

Next page | Contents page |