开发者

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

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 开发者_C百科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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜