J/Link Example: A File Chooser Dialog

Code for the file chooser dialog from section 1.3.6 of the J/Link User Guide.

You need the Swing classes installed to run this example. Swing is a standard part of the JDK 1.2 version, but 1.1.x versions may have it as well. If you get a lot of LoadJavaClass::fail messages, you either do not have Swing, or you do not have a recent-enough version of it.

To try this example, evaluate all the initialization cells (you can do this with the menu command Kernel/Evaluation/Evaluate Initialization). Then go to the Examples section.

Code

Needs["JLink`"]

FileChooserDialog[] := FileChooserDialog["Select a file:", "Open", Directory[]]

FileChooserDialog[title_String, okText_String, dir_String] :=
	JavaBlock[
		Module[{dlg, frm, dummy, chosenFile, result = Null},
			InstallJava[];
			dlg = JavaNew["javax.swing.JFileChooser"];
			If[!JavaObjectQ[dlg],
				Print["You must have the Swing classes installed for this example."];
				Return[$Failed]
			];
			dlg@setCurrentDirectory[JavaNew["java.io.File", dir]];
			dlg@setDialogTitle[title];
			(* We cannot call JavaShow to display the JFileChooser dialog because it is not
			   a subclass of Window, and also because it has its own special showDialog()
			   method that should be invoked to display it and run its modal event loop.
			   Recall that on some platforms (notably Mac and Windows), JavaShow performs
			   some internal low-level steps to allow Java windows to come to the foreground
			   in front of the notebook window. Because we cannot call JavaShow here, the
			   dialog window does not reliably come to the foreground on all platforms
			   without a little help. The trick is to create a small window that we
			   can call JavaShow on before we display the dialog. The "dummy" window on
			   which we will call JavaShow is of type Dialog, because if it was a Frame
			   it would show up in the taskbar on Windows, which we want to avoid.
			*)
			frm = JavaNew["java.awt.Frame"]; (* Need a frame to host the dummy dialog. *)
			dummy = JavaNew["java.awt.Dialog", frm];
			(* Put it offscreen. *)
			dummy@setLocation[-500, -500];
			JavaShow[dummy];
			(* On Linux and perhaps other UNIX platforms, we cannot put a dialog truly
			   offscreen until after it is shown. Thus we repeat the setLocation().
			*)
			dummy@setLocation[-500, -500];
			If[dlg@showDialog[Null, okText] === JFileChooser`APPROVEUOPTION,
				(* showDialog will not return until the dialog is dismissed. *)
				chosenFile = dlg@getSelectedFile[];
				If[chosenFile =!= Null,
					result = chosenFile@getPath[]
				]
			];
			frm@dispose[];
			dummy@dispose[];
			result
		]
	]

Examples

These examples just return the full path of the selected file. They do not perform any actual file operations..

This is a simple "Open"-style dialog:

FileChooserDialog[]

This is a simple "Save"-style dialog:

FileChooserDialog["Save data as:", "Save", Directory[]]