2021-08-20 (金) 14:02:05
  • category: swing folder: SpringLayout title: SpringLayoutの使用 tags: [SpringLayout, LayoutManager] author: aterai pubdate: 2004-03-22T10:23:19+09:00 description: SpringLayoutを使用して、各ラベルのサイズとパネルからの距離が一定の比率になるような配置を指定します。 image: https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTTwX9UR-I/AAAAAAAAAk8/TLNZjmIrPnw/s800/SpringLayout.png

概要

SpringLayoutを使用して、各ラベルのサイズとパネルからの距離が一定の比率になるような配置を指定します。
http://terai.xrea.jp/swing/springlayout/screenshot.png

サンプルコード

View in GitHub: Java, Kotlin

解説

上記のサンプルでは、SpringLayoutを使って2つのJComponentをパネル内にレイアウトしています。 SpringForm
public void addComp2(JComponent cmp){
  pnl.add(cmp);
  Component[] list = pnl.getComponents();
  SpringUtilities.makeCompactGrid(pnl,
                                  list.length, 1, //rows, cols
                                  6, 6,           //initX, initY
                                  6, 6);          //xPad, yPad
  initComps();
}
パネルのサイズが変更されるたびに、各ラベルのサイズとパネルからの距離が一定の割合になるように設定し直しています(ただしパネルの余白は無視)。
  • JLabel
    • 幅はパネルの90%、高さは55%になるよう設定
    • 左上座標は親パネルの左上からx: 5%y: 5%の位置
    • パネルと自身のWESTからの距離5%、パネルと自身のNORTHからの距離5%
  • JButton
    • 幅はパネルの40%、高さは30%になるよう設定
    • 左上座標は、親パネルの左上からx: 50%y: 65%の位置
    • パネルと自身のWESTからの距離50%、パネルと自身のSOUTHからの距離-5%

参考リンク

コメント