CharlieG
CharlieG

Reputation: 38

Why does a MouseListener not function whilst a loop is running?

I am creating a java program and want to pause the program until a mouse click using a MouseListener is identified. How would I 'pause' the program, for example using a loop, in such a way that the MouseListener still works and the program can return to the same method?

I have tried putting a loop to stop the program until a variable is true, but the MouseListener cannot work if a loop is running.

I have also attempted to put the rest of my code in the mouseClicked method, or running new methods from within mouseClicked, however another error occurred as I cannot use Graphics g anywhere except for paintComponent, for this reason it seems to me that a loop is necessary to pause the program.

Here is a simplified program which I created to show the core of the problem. (Not full code).

class Surface extends JPanel implements MouseListener{
    @Override
    public void mouseClicked(MouseEvent arg0) { 
        //Some way to unpause program
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawLine(30, 30, 200, 30);
        //The program needs to 'pause' here until a click is identified.
        System.out.println("Program finishes here");
    }    
}

The MouseListener does work, however it only seems to work if the program is dormant, and has finished all of the code in paintComponent.

Here is the code that does not work, as a loop is running.

class Surface extends JPanel implements MouseListener{
    public static boolean repeatLoop = true;

    @Override
    public void mouseClicked(MouseEvent arg0) { 
        repeatLoop = false;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawLine(30, 30, 200, 30);

        while (repeatLoop) {

        }

        System.out.println("Program finishes here");
    }    
}

I expected a loop telling the thread to sleep might work as well, but this has the same outcome and the MouseListener cannot be called.

Therefore I am asking why can a MouseListener not function when a loop is running, and is there an easy way to avert this problem and pause the program until the mouseClicked code is run.

Upvotes: 0

Views: 168

Answers (1)

Gilian Joosen
Gilian Joosen

Reputation: 486

Your loop in the paintComponent blocks the main thread, this is why this won't work. You shouldn't put that kind of logic in the paintComponent. The best thing you could do is create a separate Thread which checks for the repeatLoop. If the reapetLoop variable gets to false you could finish the application.

The paintComponent method is there just to paint on the JPanel.

Upvotes: 1

Related Questions