2

对于我正在处理的某个 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 很多次。

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

4

0 回答 0