Swing/BoxLayoutAlignment のバックアップ(No.2)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/BoxLayoutAlignment へ行く。
  - 1 (2016-05-06 (金) 14:50:05)
- 2 (2017-01-10 (火) 14:17:15)
- 3 (2017-04-07 (金) 13:51:51)
- 4 (2017-12-14 (木) 16:25:21)
- 5 (2019-08-28 (水) 19:49:05)
- 6 (2021-04-18 (日) 18:08:13)
- 7 (2022-08-20 (土) 22:15:25)
- 8 (2025-01-03 (金) 08:57:02)
- 9 (2025-01-03 (金) 09:01:23)
- 10 (2025-01-03 (金) 09:02:38)
- 11 (2025-01-03 (金) 09:03:21)
- 12 (2025-01-03 (金) 09:04:02)
- 13 (2025-06-19 (木) 12:41:37)
- 14 (2025-06-19 (木) 12:43:47)
 
- category: swing
folder: BoxLayoutAlignment
title: BoxLayoutでJLabelの中央揃えをテストする
tags: [BoxLayout, JLabel]
author: aterai
pubdate: 2015-01-26T00:15:23+09:00
description: BoxLayoutを設定したJPanelに、最小サイズを設定したJLabelを中央揃えで配置するテストを行います。
image:  
概要
BoxLayoutを設定したJPanelに、最小サイズを設定したJLabelを中央揃えで配置するテストを行います。
Screenshot

Advertisement
サンプルコード
JLabel l2 = new JLabel("abc") {
  @Override public Dimension getPreferredSize() {
    return new Dimension(50, 50);
  }
  @Override public Dimension getMinimumSize() {
    Dimension d = super.getMinimumSize();
    if (Objects.nonNull(d)) {
      int i = ((Integer) spinner.getValue()).intValue();
      d.setSize(i, i);
    }
    return d;
  }
};
l2.setOpaque(true);
l2.setBackground(Color.ORANGE);
l2.setFont(l.getFont().deriveFont(Font.PLAIN));
l2.setAlignmentX(Component.CENTER_ALIGNMENT);
l2.setAlignmentY(Component.CENTER_ALIGNMENT);
l2.setVerticalAlignment(SwingConstants.CENTER);
l2.setVerticalTextPosition(SwingConstants.CENTER);
l2.setHorizontalAlignment(SwingConstants.CENTER);
l2.setHorizontalTextPosition(SwingConstants.CENTER);
final JPanel p2 = new TestPanel();
p2.setLayout(new BoxLayout(p2, BoxLayout.Y_AXIS));
p2.add(Box.createVerticalGlue());
p2.add(l2);
p2.add(Box.createVerticalGlue());
解説
上記のサンプルは、swing - Alignment of Single Characters in Java BoxLayout on Y-Axis Is Off-Center - Stack Overflowを参考にして、BoxLayoutの中央揃えのバグ?を検証するために作成しています。
- setAlignmentX(Component.CENTER_ALIGNMENT)、- setAlignmentY(Component.CENTER_ALIGNMENT)を設定した- JLabelを作成
- BoxLayout.X_AXISの- Boxに、この- JLabelが左右中央に配置されるよう、- Box.createHorizontalGlue()で挟んで追加
- BoxLayout.Y_AXISの- Boxに、この- JLabelが上下中央に配置されるよう、- Box.createVerticalGlue()で挟んで追加
- JLabel#getMinimumSize()の返す値を- JSpinnerで変更すると、値が奇数になる場合で揃えがずれてしまう
参考リンク
- How to Use BoxLayout (The Java™ Tutorials > Creating a GUI With JFC/Swing > Laying Out Components Within a Container)
- swing - Alignment of Single Characters in Java BoxLayout on Y-Axis Is Off-Center - Stack Overflow