View Javadoc

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