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