如何在保持纵横比的同时调整 JFrame 的大小?

And*_*Kor 2 java swing resize jframe

我希望用户能够调整 JFrame 的宽度/高度的大小,同时保持其宽度和高度之间的相同比率。换句话说,我想强制高度改变,宽度保持相同的框架形状。

public void componentResized(ComponentEvent arg0)
    {
        int setHeight = arg0.getComponent().getHeight();
        int setWidth = arg0.getComponent().getWidth();
        double newWidth = 0;
        double newHeight = 0;
        {
            if(setHeight != oldHeight)
            {
                heightChanged = true;
            }
            if(setWidth != oldWidth)
            {
                widthChanged = true;
            }
        }
        {
            if(widthChanged == true && heightChanged == false)
            {
                newWidth = setWidth;
                newHeight = setWidth*HEIGHT_RATIO;
            }
            else if(widthChanged == false && heightChanged == true)
            {
                newWidth = setHeight * WIDTH_RATIO;
                newHeight = setHeight;
            }
            else if(widthChanged == true && heightChanged == true)
            {
                newWidth = setWidth;
                newHeight = setWidth*HEIGHT_RATIO;
            }
        }

        int x1 = (int) newWidth;
        int y1 = (int) newHeight;
        System.out.println("W: " + x1 + " H: " + y1);
        Rectangle r = arg0.getComponent().getBounds();
        arg0.getComponent().setBounds(r.x, r.y, x1, y1);
        widthChanged = false;
        heightChanged = false;
        oldWidth = x1;
        oldHeight = y1;
    }
Run Code Online (Sandbox Code Playgroud)

Syd*_*ove 5

看看 J 帧的纵横比调整大小

我想这就是你所需要的。

@Override
public void componentResized(ComponentEvent arg0) {
    int W = 4;  
    int H = 3;  
    Rectangle b = arg0.getComponent().getBounds();
    arg0.getComponent().setBounds(b.x, b.y, b.width, b.width*H/W);

}
Run Code Online (Sandbox Code Playgroud)

  • 这对于他的要求来说效果很好,但是在高度变化的情况下,这将会失败。您需要获取新的宽度、新的高度,并将该比率与所需的比率进行比较,然后确定要更改的内容 (2认同)