componentResized event for Component in Java, but only execute when mouse released

早过忘川 提交于 2019-12-23 12:53:30

问题


I need to do some calculations when one of my Components (a Canvas) gets resized. Unfortunately the calculations can take a few hundred milliseconds which causes the resize to lag heavily while being done. I'd like to solve that by only doing the calculation when the resizing ended (I guess when the mouse button gets released). How can I achieve that? So far I only have the following:

MyComponent.addComponentListener(new ComponentAdapter() {
    @Override
    public void componentResized(ComponentEvent e) {
        super.componentResized(e);
        // some calculation
    }       
});

Thanks.

PS: I know that for a JFrame the resized event gets fired only after the mouse button is released, but unfortunately I cannot put my Component into a JFrame or having it extend a JFrame.


回答1:


then you can start javax.swing.Timer with some delay and on resize only restart Timer and by invoking Action or AbstractAction you can calculete anything and output to the GUI will be on EDT




回答2:


You could set a flag in componentResized() and have a MouseListener do the actual work.




回答3:


I would do a MouseListener like this:

public class MouseHandler implements MouseListener
{
    public void mousePressed(MouseEvent e)
    {
        if(!running)
        {
            thread = new Thread(this);
            thread.start();
            running = true;
        }
    }

    public void mouseReleased(MouseEvent e)
    {
        running = false;
        thread = null
    }

    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
    public void mouseClicked(MouseEvent e){}

    public void run()
    {
        while(running)
        {
            try
            {
                //repaint the component or move it or somthing.
                Thread.sleep(1000);
                // repaint delay
            }catch(Exception e){e.printStackTrace();}
        }
    }

    Thread thread;
    boolean running;
}

You could throw in a MouseMotionListener if you want to change the location of the component



来源:https://stackoverflow.com/questions/6738664/componentresized-event-for-component-in-java-but-only-execute-when-mouse-releas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!