Reputation: 388
What I want to achieve is that
Problem:
I used the following approach:
public static void main(String[] args) {
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
public void eventDispatched(AWTEvent event) {
WindowEvent windowEvent = ((WindowEvent) event);
System.out.println(System.currentTimeMillis() + " " + windowEvent);
switch (windowEvent.getID()) {
case WindowEvent.WINDOW_OPENED:
System.out.println("Hiding");
windowEvent.getComponent().setVisible(false);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Showing");
windowEvent.getComponent().setVisible(true);
break;
}
}
}, AWTEvent.WINDOW_EVENT_MASK + AWTEvent.WINDOW_STATE_EVENT_MASK);
JOptionPane.showMessageDialog(null,
"Eggs are not supposed to be green.",
"Inane custom dialog",
JOptionPane.INFORMATION_MESSAGE);
}
It produces the following output:
1347602481337 java.awt.event.WindowEvent[WINDOW_ACTIVATED,opposite=null,oldState=0,newState=0]
on dialog0
1347602481337 java.awt.event.WindowEvent[WINDOW_GAINED_FOCUS,opposite=null,oldState=0,newState=0] on dialog0
1347602481337 java.awt.event.WindowEvent[WINDOW_OPENED,opposite=null,oldState=0,newState=0] on dialog0
Hiding
Showing
1347602486377 java.awt.event.WindowEvent[WINDOW_LOST_FOCUS,opposite=null,oldState=0,newState=0] on dialog0
1347602486377 java.awt.event.WindowEvent[WINDOW_DEACTIVATED,opposite=null,oldState=0,newState=0] on dialog0
1347602486377 java.awt.event.WindowEvent[WINDOW_ACTIVATED,opposite=null,oldState=0,newState=0] on dialog0
1347602486377 java.awt.event.WindowEvent[WINDOW_GAINED_FOCUS,opposite=null,oldState=0,newState=0] on dialog0
1347602486377 java.awt.event.WindowEvent[WINDOW_LOST_FOCUS,opposite=null,oldState=0,newState=0] on dialog0
1347602486377 java.awt.event.WindowEvent[WINDOW_DEACTIVATED,opposite=null,oldState=0,newState=0] on dialog0
1347602486377 java.awt.event.WindowEvent[WINDOW_CLOSED,opposite=null,oldState=0,newState=0] on dialog0
1347602486377 java.awt.event.WindowEvent[WINDOW_CLOSED,opposite=null,oldState=0,newState=0] on dialog0
1347602486377 java.awt.event.WindowEvent[WINDOW_CLOSED,opposite=null,oldState=0,newState=0] on frame0
My question is, what I did to wrong? Is this per design or do I make an error, do I use the classes the wrong way? If yes, what would be the correct way?
Upvotes: 1
Views: 1460
Reputation: 36611
What you did wrong is sleeping on the Event Dispatch Thread:
windowEvent.getComponent().setVisible(false);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Showing");
windowEvent.getComponent().setVisible(true);
By blocking the EDT for 5 seconds, nothing can get repainted. Use a Timer
instead.
See the Concurrency in Swing tutorial for more information.
Upvotes: 3