What I want to achieve is that
- In a certain state, a class should automatically hide dialogs displayed by other classes
- The hidden dialogs should be displayed when state of program changes
Problem:
- This does not work with JOptionPanes
- The JOptionPanes are hidden and displayed again, but then they are automatically closed, so I only see them again for part of a second
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?
What you did wrong is sleeping on the Event Dispatch Thread:
By blocking the EDT for 5 seconds, nothing can get repainted. Use a
Timerinstead.See the Concurrency in Swing tutorial for more information.