while loop ignore the event listener
so when i run this code to try to change the background the GUI crashes and gets stuck in a infinite while loop ignoring the event listeners. here is the code:
private Panel getPanel1() {
if (panel1 == null) {
panel1 = new Panel();
panel1.setLayout(new GridBagLayout());
while(frame.isVisible()){
panel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
frame.setVisible(false);
}
});
int r = (int) (Math.random()*255);
int g = (int) (Math.random()*255);
int b = (int) (Math.random()*255);
Color c = new Color(r, g, b);
panel1.setBackground(c);
try {
Thread.sleep(4000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
panel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
/*panel1.setVisible(false);
frame.setVisible(false);*/
System.exit(0);
}
});
}
}
return panel1;
}
instead of exiting the loop of terminating the program or event changing the ba开发者_运维技巧ckground it just displays the panel and does nothing else and i have to force it to quit. what should i do?
You're effectively blocking the UI thread by calling sleep
in a loop. In that loop you're also adding two listeners on every iteration too, which is quite bizarre.
Don't block the UI thread. Let the GUI framework take care of delivering events etc. Basically you need to take an event-based approach to UI, rather than the approach you currently are taking, which will never let any events get despatched (as you're never returning control to the caller).
Create the panel, add the appropriate event listener, and then just return it to the caller. If you want to change the background colour every 4 seconds, you should do that via a timer so that it's not blocking the UI thread waiting for the 4 seconds to elapse.
精彩评论