BlacKnight BK BlacKnight BK -4 years ago 50
Java Question

How to maintain the aspect ratio of a JFrame

I am creating an application that I believe would be better if it could maintain its aspect ratio when expanding\minimizing. I set the minimum size to be 1000x800 and would like it to maintain this ratio of 5:4.

Is there a method for that already or will I need to add an event handler myself that checks if the frame has been resized it will give it the closest size possible?

PS.If question is repeated I am sorry, I could not find it

Answer Source

Try this:

@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);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download