JFrame顺利调整内存泄漏

时间:2012-09-03 18:20:21

标签: memory resize jframe memory-leaks

对于我正在处理的某个GUI项目,我有一个JFrame,其中包含一个带有标签等的窗格。对于每个选项卡,它有不同的大小,所以我想将窗口大小调整为该大小,但我不想通过调用setSize来捕捉大小,我希望它更平滑地滑动到大小。 我用以下基本代码实现了这个目标:

    private class Resizer implements Runnable {

    private int nw, nh, runs, sizex, sizey;
    private float width, height, wpms, hpms, decay = 0.994f;
    private Future future;

    public Resizer(int newwidth, int newheight){

        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        sizex = d.width;
        sizey = d.height;
        width = frame.getWidth();
        height = frame.getHeight();
        wpms = (float)(newwidth - frame.getWidth()) / 1000;
        wpms *= 6;
        hpms = (float)(newheight - frame.getHeight()) / 1000;
        hpms *= 6;
        nw = newwidth;
        nh = newheight;
        runs = 0;

    }

    public void run(){

        runs++;
        if (runs == 1000){

            frame.setSize(nw, nh);
            future.cancel(true);
            canResize = true;
            return;

        }

        width += wpms;
        wpms *= decay;
        height += hpms;
        hpms *= decay;
        if (height + frame.getY() > sizey)
            frame.setLocation(frame.getX(), frame.getY() - (int)(frame.getY() + height - sizey));
        frame.setSize((int) width, (int) height);
        frame.repaint();

    }

    public void setFuture(Future f){

        future = f;

    }

}

public boolean resizeTo(int width, int height){

    if (canResize){

        canResize = false;
        Resizer r = new Resizer(width, height);
        r.setFuture(timer.scheduleAtFixedRate(r, 0, 2, TimeUnit.MILLISECONDS));
        return true;

    }
    return false;

}

但是有一个问题显然存在内存泄漏(调整大小几次后从20k变为150k),我发现在调整大小时使用了setSize很多次。

有没有办法修复泄漏或其他调整大小的方法?

0 个答案:

没有答案