View Javadoc

1   package com.eviware.soapui.support.swing;
2   
3   import java.awt.Frame;
4   import java.awt.event.WindowAdapter;
5   import java.awt.event.WindowEvent;
6   import java.lang.reflect.InvocationHandler;
7   import java.lang.reflect.Method;
8   import java.lang.reflect.Proxy;
9   
10  import javax.swing.JFrame;
11   
12  // @author Santhosh Kumar T - santhosh@in.fiorano.com 
13  public class ModalFrameUtil {
14      static class EventPump implements InvocationHandler {
15          Frame frame;
16   
17          public EventPump(Frame frame) {
18              this.frame = frame;
19          }
20   
21          public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
22              return frame.isShowing();
23          }
24   
25          // when the reflection calls in this method has to be
26          // replaced once Sun provides a public API to pump events.
27          public void start() throws Exception {
28              Class<?> clazz = Class.forName("java.awt.Conditional");
29              Object conditional = Proxy.newProxyInstance(
30                      clazz.getClassLoader(),
31                      new Class[] { clazz },
32                      this);
33              Method pumpMethod = Class.forName("java.awt.EventDispatchThread")
34                      .getDeclaredMethod("pumpEvents", new Class[] { clazz } );
35              pumpMethod.setAccessible(true);
36              pumpMethod.invoke(Thread.currentThread(), new Object[] { conditional } );
37          }
38      }
39   
40      // show the given frame as modal to the specified owner.
41      // NOTE: this method returns only after the modal frame is closed.
42      public static void showAsModal(final Frame frame, final Frame owner) {
43          frame.addWindowListener(new WindowAdapter() {
44              public void windowOpened(WindowEvent e) {
45                  owner.setEnabled(false);
46              }
47   
48              public void windowClosing(WindowEvent e) {
49                 owner.setEnabled(true);
50                 frame.removeWindowListener(this);
51              }
52              
53              public void windowClosed(WindowEvent e) {
54                 owner.setEnabled(true);
55                 frame.removeWindowListener(this);
56              }
57          });
58   
59          owner.addWindowListener(new WindowAdapter() {
60              public void windowActivated(WindowEvent e) {
61                  if(frame.isShowing()) {
62                      frame.setExtendedState(JFrame.NORMAL);
63                      frame.toFront();
64                  } else {
65                      owner.removeWindowListener(this);
66                  }
67              }
68          });
69   
70          frame.setVisible(true);
71          try {
72              new EventPump(frame).start();
73          } catch(Throwable throwable) {
74              throw new RuntimeException(throwable);
75          }
76      }
77  }