J/Link Example: A Modal Input Dialog

Code for the GetAngle function from section 1.3.5 of the J/Link User Guide.

This example demonstrates the use of DoModal to create a simple modal input dialog that returns a result to Mathematica.

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 Example section.

Code

Needs["JLink`"]

GetAngle[] :=
	JavaBlock[
		Module[{frm, inputField, cbGroup, degBox, radBox, label, okButton, cancelButton, wasOKButton, angle},

			InstallJava[];

			frm = JavaNew["com.wolfram.jlink.MathFrame"];
			label = JavaNew["java.awt.Label", "Enter an angle:"];
			inputField = JavaNew["java.awt.TextField"];
			cbGroup = JavaNew["java.awt.CheckboxGroup"];
			degBox = JavaNew["java.awt.Checkbox", "degrees", cbGroup, True];
			radBox = JavaNew["java.awt.Checkbox", "radians", cbGroup, False];
			okButton = JavaNew["java.awt.Button", "OK"];
			cancelButton = JavaNew["java.awt.Button", "Cancel"];
			
			frm@setLayout[Null];
			frm@add[label];
			frm@add[inputField];
			frm@add[degBox];
			frm@add[radBox];
			frm@add[okButton];
			frm@add[cancelButton];
			
			frm@setBounds[200, 200, 200, 160];
			label@setBounds[20, 30, 150, 20];
			inputField@setBounds[20, 70, 60, 28];
			degBox@setBounds[100, 60, 80, 20];
			radBox@setBounds[100, 80, 80, 20];
			okButton@setBounds[40, 120, 50, 20];
			cancelButton@setBounds[100, 120, 50, 20];
			frm@setResizable[False];
			
			okButton@addActionListener[JavaNew["com.wolfram.jlink.MathActionListener", "(EndModal[]; True)&"]];
			cancelButton@addActionListener[JavaNew["com.wolfram.jlink.MathActionListener", "(EndModal[]; False)&"]];
			
			JavaShow[frm];

			frm@setModal[];
			wasOKButton = DoModal[];
			(* Even though the window may have been closed, it is perfectly OK to extract values fom the
			   controls in the window.
			*)
			If[TrueQ[wasOKButton],
				angle = ToExpression[inputField@getText[]];
				If[angle =!= Null && degBox@getState[], angle *= Pi/180],
			(* else *)
				(* We will get here if the Cancel button was clicked (wasOKButton will be False),
				   or if the dialog was closed by clicking in its close box (wasOKButton will be Null).
				*)
				angle = $Failed
			];
			(* If the cancel or OK buttons were clicked, frm is still visible, so we dispose it here. *)
			frm@dispose[];
			angle
		]
	]

Example

GetAngle[]