J/Link Example: A ProgressBar Dialog

Code for the progress-bar dialog from section 1.3.4 of the J/Link User Guide.

This example demonstrates a simple "non-interactive" user interface created from Mathematica (as described in section 1.2.7 of the User Guide). It makes no calls back to Mathematica and does not return a result to Mathematica.

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

Code

Needs["JLink`"]

ShowProgressBar[title_String:"Computation Progress", caption_String:"Percent complete:", percent_Integer:0] :=
	Module[{frame, panel, label, bar},
		JavaBlock[
			InstallJava[];
			bar = JavaNew["javax.swing.JProgressBar"];
			If[!JavaObjectQ[bar],
				Print["You must have the Swing classes installed for this example."];
				Return[$Failed]
			];
			frame = JavaNew["javax.swing.JFrame", title];
			frame@setSize[300, 110];
			frame@setResizable[False];
			frame@setLocation[400, 400];
			panel = JavaNew["javax.swing.JPanel"];
			panel@setLayout[Null];
			frame@getContentPane[]@add[panel];
			label = JavaNew["javax.swing.JLabel", caption];
			label@setBounds[20, 10, 260, 20];
			panel@add[label];
			bar@setBounds[20, 40, 260, 30];
			bar@setMinimum[0];
			bar@setMaximum[100];
			bar@setValue[percent];
			panel@add[bar];
			JavaShow[frame];
			bar
		]
	]

DestroyProgressBar[bar_?JavaObjectQ] :=
	JavaBlock[
		LoadClass["javax.swing.SwingUtilities"];
		SwingUtilities`windowForComponent[bar]@dispose[];
		ReleaseJavaObject[bar]
	]


ProgressBarDemo[] :=
	Module[{bar, n},
		bar = ShowProgressBar[];
		bar@setString["0%"];
		bar@setStringPainted[True];
		n = 0;
		While[n <= 5,
			bar@setValue[n/5 * 100];
			bar@setString[ToString[n/5 * 100] <> "%"];
			Pause[1]; (* This simulates the time-consuming computation. *)
			n++
		];
		DestroyProgressBar[bar];
	]

Example

ProgressBarDemo[]