How to wait for a mouse click

Curious Guy 007 picture Curious Guy 007 · Oct 1, 2012 · Viewed 11.1k times · Source
class GameFrameClass extends javax.swing.JFrame  {

    public void MyFunc()
    {
        UserButton.setText(Str);
        UserButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                UserButtonActionPerformed(evt);
            }
        });
        getContentPane().add(UserButton);
    }

    private void UserButtonActionPerformed(java.awt.event.ActionEvent evt) {

        //print some stuff after mouse click
    }
}

In someother class i define this function

void functionAdd()
{
    GameFrameClass gfc = new GameFrameClass()
    gfc.MyFunc()
    System.out.println("PRINT THIS AFTER MOUSE CLICK")  
}

If someone can look into this code. I want to wait on the mouse click . Is there a way i can print the line System.out.println("PRINT THIS AFTER MOUSE CLICK") after the mouse is being clicked . For now this happens immediately and i am not able to wait for the mouse click . Is there a way of doing it ? Apart from doing it inside the function UserButtonActionPerformed() . Please let me know .

Answer

MadProgrammer picture MadProgrammer · Oct 1, 2012

This is a really "bad" way to do it...

private void UserButtonActionPerformed(java.awt.event.ActionEvent evt) {
    addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent evt) {
            System.out.println("PRINT THIS AFTER MOUSE CLICK");
            removeMouseListener(this);
        }
    });
}

A better way would be to have a flag in the actionPerformed method that would "enable" a mouse listener (which you added earlier). This listener would check the flag on each click and when set to true it would flip the flag (to false) and process the event...