2

I've searched for this question but didn't really find a clear, helpful answer. I'm building my first Java UI apps1 (using Swing) and I was wondering one thing: how can I force the resizing of windows to happen scaled? It's something aesthetically important for my upcoming program. Could anyone help me with this? Thanks! And guys, I'm not asking for 'just give me a solution', I KNOW you guys hate that, I just need someone helping me reach it!

  1. It's a little Boggle game. I have a grid with JButton instances to simulate the dices of Boggle (these need to be clicked to form words), and when I resize the window I want the dices to keep being square, they get rectangular and that's not really how it should be.
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
E. V. d. B.
  • 815
  • 2
  • 13
  • 30
  • "how can I force the resizing of windows to happen scaled?"... I'm not sure what your asking for here. Do you mean to maintain the frame's width-to-height ratio if the user resizes it? – splungebob Feb 22 '13 at 16:16
  • @splungebob Exactly that yeah! The width-to-height ratio should stay the same ;) – E. V. d. B. Feb 22 '13 at 16:17

2 Answers2

2

You can listen for component resized events on your window and set the desired scaled height when the width is changed.

addComponentListener(new ComponentAdapter() {
  public void componentResized(ComponentEvent e) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        // TODO: calculate new size and set it
      }
    });
  }
});

However, you will have to tweak this such as you avoid flickering.

Dan D.
  • 32,246
  • 5
  • 63
  • 79
2

You may be able to adapt the approach shown in JDigit, seen here, which resamples a large BufferedImage to fill the component; resize the frame to see the effect. You can enforce the 1:1 aspect ratio by setting the width and height to the same value: Math.min(width, height). A related example is shown here.

image

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045