• 追加された行はこの色です。
  • 削除された行はこの色です。
---
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`の幅と高さの比率が一定になるように制限します。

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

* サンプルコード [#sourcecode]
#code(link){{
private static final int MW = 320;
private static final int MH = 200;
// ...
frame.addComponentListener(new ComponentAdapter() {
  @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);
  }
});
}}

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

- `Windows 10` + `JDK 1.8.0_141`の環境では正常に動作しない
- `Windows 10` + `Java 8`以降では正常に動作しない

* 参考リンク [#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