• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JFrameの縦横比を一定にする
#navi(../)
*JFrameの縦横比を一定にする [#kdb0783d]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2006-11-06~
更新日:&lastmod;
---
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
---
* 概要 [#summary]
`JFrame`の幅と高さの比率が一定になるように制限します。

#contents
#download(https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTKJeWlAAI/AAAAAAAAAVg/GMclfo0TYBM/s800/ConstrainedProportions.png)

**概要 [#g29433d2]
JFrameの幅と高さの比率が一定になるように制限します。

#screenshot

**サンプルコード [#ff7d99b8]
#code{{
final int mw = 320;
final int mh = 200;
* サンプルコード [#sourcecode]
#code(link){{
private static final int MW = 320;
private static final int MH = 200;
// ...
frame.addComponentListener(new ComponentAdapter() {
  public void componentResized(ComponentEvent e) {
  @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);
    int fh = MH * fw / MW;
    frame.setSize(MW > fw ? MW : fw, MH > fh ? MH : fh);
  }
});
}}
-&jnlp;
-&jar;
-&zip;

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

**参考リンク [#qf286589]
-[[JFrameの最小サイズ>Swing/MinimumFrame]]
-[[DynamicLayoutでレイアウトの動的評価>Swing/DynamicLayout]]
- `Windows 10` + `Java 8`以降では正常に動作しない

**コメント [#ndb3de0e]
* 参考リンク [#reference]
- [[JFrameの最小サイズ>Swing/MinimumFrame]]
- [[DynamicLayoutでレイアウトの動的評価>Swing/DynamicLayout]]

* コメント [#comment]
#comment
- これはドラッグ中は自由なサイズでボタンを離したときにサイズが正しく変更されます。ドラッグ中も正しい比率になるのは無理でしょうか? --  &new{2007-11-10 (土) 00:17:13};
-- ども。今の`Java`だけだと難しいかもしれません。すこし調べてみます。 -- &user(aterai); &new{2007-11-12 (月) 11:45:22};

#comment