How To Enforce Step-By-Step Execution--A Swing Hack

You can suspend a Java application (e.g. a JUnit execution) with a modal dialog. The most convenient way is to use the following one-liner:

javax.swing.JOptionPane.showConfirmDialog(null, "Something happened:…");

This trick will usually cause on the application server the following exception: java.awt.HeadlessException, but works perfectly in unit, integration tests on the client side etc.
Hint: setting a breakpoint may be even faster :-)


I usually do:

new CountDownLatch(1).await() to let the test hanging, avoid headlessexception but needs a Ctrl+C ;) (fine for small test)

Posted by rmannibucau on July 17, 2012 at 04:23 PM CEST #

In order to block the whole application, you can create the dialog Shell with the style SWT.APPLICATION_MODAL, open it, and then pump the UI events until the shell is disposed:

Display display = Display.getDefault();
Shell dialogShell = new Shell(display, SWT.APPLICATION_MODAL);
// populate dialogShell;
while (!dialogShell.isDisposed()) {
if (!display.readAndDispatch()) {
If you want to block input only to the parent, try using the style SWT.PRIMARY_MODAL, though the Javadocs specify (as for the other modal styles) that this is a hint; i.e., that different SWT implementations may not exactly handle it the same way. Likewise, I don't know of an implementation that would honor the SWT.SYSTEM_MODAL style.

Posted by recurring hives on August 11, 2012 at 09:19 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments