Reputation: 154
I want the user to be able to resize the JFrame's width/height, while maintaining the same ratio between its width and height. In other words, I want to force the height to change with the width keeping the same frame shape.
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;
}
Upvotes: 2
Views: 9373
Reputation: 301
Try using a componentEvent to signal when the frame is resized. When the frame is resized keep track of which dimension (x or y) was changed. Use the getSize() method to get the frame dimensions and then get .getWidth() or .getHeight() to get the new size the frame was adjusted to. Use the new size of the changed dimension to calculate the desired size for the other dimension and set the size of the frame using .setSize(int width, int height).
This might have problems if you change both the width and height in the same resizing, if so you can always base the height off the width or vice versa
Upvotes: 2
Reputation: 833
Have a look at J frame resizing in an aspect ratio
I think this is what you need.
@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);
}
Upvotes: 5