while loop ignore the event listener

Posted by Tamer on Stack Overflow See other posts from Stack Overflow or by Tamer
Published on 2009-12-05T19:12:30Z Indexed on 2010/04/18 0:13 UTC
Read the original article Hit count: 558

Filed under:
|
|

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 background it just displays the panel and does nothing else and i have to force it to quit. what should i do?

© Stack Overflow or respective owner

Related posts about awt

Related posts about swing