Skip to content
Advertisement

why all thing is stop when i’ll use while loop in MouseEntered() Function ?? In Java

My gui programme that contains (JPanel ,JFrame ,JLabel) JLabel : I Coded it To move from (0x, 0y) To (200x ,0y) Pixel by Pixel . it will start when i put the mouse on the panel called “p” ,but when i try to run this programme it’s start correctly ,but when i put my mouse on the panel all thing stop to a few seconds The Label Moved to Point (200x, 0y) Any One Had Any Answer To Solve This Problem.

The Class Had The Problem :-

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class JFrameClass extends JFrame{
    JPanel p = new JPanel();
    JLabel l = new JLabel();
    
    public JFrameClass() {
        // TODO Auto-generated constructor stub
        setSize(800, 800);
        setLayout(null);
        setLocationRelativeTo(null);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        l.setBounds(0, 0, 50, 50);
        l.setBackground(new Color(16, 16, 16));
        l.setOpaque(true);
        
        p.setBounds(320, 320, 100, 100);
        p.setBackground(new Color(16, 16, 16));
        p.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent evt) {
                boolean wd = true;
                int x = 0;
                while(true) {
                    if(x == 200) wd = false;
                    if(!wd) break;
                    l.setLocation(x, 0);
                    x++;
                    try {
                        Thread.sleep(10);
                    }catch(Exception e) {
                        
                    }
                }   
            }
        });
        
        
        add(p);
        add(l);
        
        
        
        setVisible(true);
    }
}

The Main Class That Run The JFrameClass class :-

public class Main {
    public static void main(String[] args) {
        new JFrameClass();
        
    }
}

Advertisement

Answer

You’re running your code on the Event-Dispatch-Thread. That’s a no-no. Put the code in your mouseEntered into a SwingWorker.

SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
                 protected Void doInBackground() throws Exception {
                     for (int x = 0; x < 200; x++) {
                         l.setVisible(false);
                         l.setLocation(x, 0);
                         l.setVisible(true);
                         try {
                             Thread.sleep(10);
                         }catch(Exception e) {
                             
                         }
                     }
                     return null;
                 }
             };
             worker.execute();
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement