• title: SpringLayoutの使用 tags: [SpringLayout, LayoutManager] author: aterai pubdate: 2004-03-22 description: SpringLayoutを使用して、各ラベルのサイズとパネルからの距離が一定の比率になるような配置を指定します。

概要

SpringLayoutを使用して、各ラベルのサイズとパネルからの距離が一定の比率になるような配置を指定します。

サンプルコード

private static void setScaleAndAdd(
    JComponent parent, SpringLayout layout, JComponent child,
    float sx, float sy, float sw, float sh) {
  Spring panelw = layout.getConstraint(SpringLayout.WIDTH,  parent);
  Spring panelh = layout.getConstraint(SpringLayout.HEIGHT, parent);

  SpringLayout.Constraints c = layout.getConstraints(child);
  c.setX(Spring.scale(panelw, sx));
  c.setY(Spring.scale(panelh, sy));
  c.setWidth(Spring.scale(panelw,  sw));
  c.setHeight(Spring.scale(panelh, sh));

  parent.add(child);
}

// public void initLayout() {
//   SpringLayout layout = new SpringLayout();
//   Insets i = panel.getInsets();
//   int w = panel.getWidth()  - i.left - i.right;
//   int h = panel.getHeight() - i.top  - i.bottom;
//
//   l1.setPreferredSize(new Dimension(w * 90 / 100, h * 55 / 100));
//   l2.setPreferredSize(new Dimension(w * 40 / 100, h * 30 / 100));
//
//   layout.putConstraint(SpringLayout.WEST,  l1, w * 5 / 100,
//                        SpringLayout.WEST,  panel);
//   layout.putConstraint(SpringLayout.NORTH, l1, h * 5 / 100,
//                        SpringLayout.NORTH, panel);
//   layout.putConstraint(SpringLayout.WEST,  l2, w * 50 / 100,
//                        SpringLayout.WEST,  panel);
// //layout.putConstraint(SpringLayout.WEST, l2, 0, SpringLayout.WEST, l1);
//   layout.putConstraint(SpringLayout.SOUTH, l2, -h * 5 / 100,
//                        SpringLayout.SOUTH, panel);
//
//   panel.setLayout(layout);
//   panel.revalidate();
// }
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、SpringLayoutを使って2つのJComponentをパネル内にレイアウトしています。

パネルのサイズが変更されるたびに、各ラベルのサイズとパネルからの距離が一定の割合になるように設定し直しています(ただしパネルの余白は無視)。

  • JLabel
    • 幅はパネルの90%、高さは55%
    • 左上座標は、親パネルの左上からx:5%, y:5%の位置
    • パネルと自身のWESTからの距離5%、パネルと自身のNORTHからの距離5%
  • JButton
    • 幅はパネルの40%、高さは30%
    • 左上座標は、親パネルの左上からx:50%, y:65%の位置
    • パネルと自身のWESTからの距離50%、パネルと自身のSOUTHからの距離-5%

SpringLayoutでは原点は左上で、右方向、下方向に正の値を取る為、例えばパネルの南辺からコンポーネントの南辺までの距離を指定する場合は、layout.putConstraintする際にマイナスの値を指定する必要があります。

距離を0にすることも可能で、例えばサンプルコードのコメントアウトされたような指定をすると、ラベル12を左揃えで並べることができます。

コメント