TITLE:JFrameの縦横比を一定にする

JFrameの縦横比を一定にする

編集者:Terai Atsuhiro~

作成日:2006-11-06
更新日:2022-05-18 (水) 06:21:43
  • category: swing folder: ConstrainedProportions title: JFrameの縦横比を一定にする tags: [JFrame] author: aterai pubdate: 2006-11-06T14:28:33+09:00 description: JFrameの幅と高さの比率が一定になるように制限します。 image: https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTKJeWlAAI/AAAAAAAAAVg/GMclfo0TYBM/s800/ConstrainedProportions.png

概要

JFrameの幅と高さの比率が一定になるように制限します。

概要

JFrameの幅と高さの比率が一定になるように制限します。

サンプルコード

#spanend
#spanadd
private static final int MW = 320;
#spanend
#spanadd
private static final int MH = 200;
#spanend
#spanadd
// ...
#spanend
#spanadd
frame.addComponentListener(new ComponentAdapter() {
#spanend
  @Override public void componentResized(ComponentEvent e) {
    int fw = frame.getSize().width;
    int fh = MH * fw / MW;
    frame.setSize(MW > fw ? MW : fw, MH > fh ? MH : fh);
  }
#spanadd
});
#spanend
#spanadd
View in GitHub: Java, Kotlin

#screenshot

解説

上記のサンプルでは、JFrameのサイズを変更した後その幅から縦横比が変更前と同じになるような高さを計算してJFrame#setSize(int,int)で設定し直しています。

サンプルコード

#spanend
 final int mw = 320;
 final int mh = 200;
 frame.addComponentListener(new ComponentAdapter() {
   public void componentResized(ComponentEvent e) {
     int fw = frame.getSize().width;
     int fh = mh*fw/mw;
     frame.setSize((mw>fw)?mw:fw, (mh>fh)?mh:fh);
   }
 });
#spandel
  • &jnlp;
  • &jar;
  • &zip;
  • Windows 10 + Java 8以降では正常に動作しない

解説

上記のサンプルでは、JFrameのサイズを変更した後、その幅から縦横比が同じになるような高さを計算して、JFrame#setSize(int,int)でサイズを設定し直しています。

参考リンク

参考リンク

コメント