views:

329

answers:

1

Is it possible to lock the aspect ratio of a JFrame in Java Swing?

For example, if my window is 200px by 200px, and the user wants to resize it, I want the ratio between the width and the height at 1:1, so that if the new width is 400px, the new height is forced to 400px.

I'm aware of ComponentListener and componentResized, but I'm having difficulty not getting it to go into an infinite loop of resizing, because I'm resizing the window in a resize listener.

Thanks!

+2  A: 

I don't have a specific answer to your question, but I have often found that the way to avoid the "infinite loop of resizing" you talk about is to defer your call to resize the window:

boolean correctAspectRatio = ...; // check to see if new size meets aspect ratio requirements

if (!correctAspectRatio) {
  final Frame _frame = this;
  final int _width = ...; // calculated width
  final int _height = ...; // calculated height

  SwingUtilities.invokeLater(new Runnable(){
    public void run() {
      _frame.setSize(_width, _height);
    }
  });
}
David Sykes
Even if I do this, it will still go into a loop of resizing, it's just not as noticeable. Try doing _width + 20, _height + 20, and you'll see what I mean.
nasufara
I am assuming you don't call the resize if the size meets the aspect ratio, right? See my edited answer
David Sykes
Ah, that worked great. I suppose there really isn't much of a way to do this while the user is resizing, but this way works fine. Thanks.
nasufara