Swing/ConstrainedProportions のバックアップの現在との差分(No.1)
TITLE:JFrameの縦横比を一定にする
JFrameの縦横比を一定にする
編集者:Terai Atsuhiro~
作成日:2006-11-06
更新日:2022-05-18 (水) 06:21:43
概要
JFrame
の幅と高さの比率が一定になるように制限します。
Screenshot
Advertisement
概要
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)でサイズを設定し直しています。参考リンク
参考リンク
コメント
- これはドラッグ中は自由なサイズでボタンを離したときにサイズが正しく変更されます。ドラッグ中も正しい比率になるのは無理でしょうか? --
- ども。今の
Java
だけだと難しいかもしれません。すこし調べてみます。 -- aterai
- ども。今の