gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 20:16:45 24 4
gpt4 key购买 nike

我希望用户能够调整 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;
}

最佳答案

看看 J frame resizing in an aspect ratio

我认为这就是您所需要的。

@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);

}

关于java - 如何在保持纵横比的同时调整 JFrame 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19865022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com