简体   繁体   中英

Mouse event wait freezes when called from button

I have a method which brings up a transparent window overlay so I can indicate corner points of a rectangular onscreen area via clicks.

public Point getClickPoint(){
        JFrame frame = new JFrame("");
        MyMouseListener mouseL = new MyMouseListener();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setUndecorated(true);
        makeTranslucent(frame, Float.valueOf(0.40f));
        frame.setSize(toolkit.getScreenSize());
        frame.setVisible(true);

      frame.addMouseListener(mouseL);
        while(!mouseL.done){
            try {
                Thread.sleep(4);
                } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
 }

When I call this in a normal way it works fine, but if I call it by a button press, then it hangs, doesn't register clicks and eventually freezes.

 Button.addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent actionEvent) {
        getClickPoint();
    }
}

Is this something to do with the fact this is called originally by an action listener?

You are blocking the Event Dispatch Thread . Since the actionPerformed method will be called on the EDT, your while loop in getClickPoint will prevent the EDT from processing any events (including the mouse events you are waiting for), causing your program to become unresponsive.

If you need to perform time expensive tasks (such as blocking), take a look at SwingWorker .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM