Swing/DockingConstraint のバックアップ(No.17)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/DockingConstraint へ行く。
- 1 (2006-09-18 (月) 18:01:15)
- 2 (2006-09-19 (火) 06:35:05)
- 3 (2007-08-14 (火) 12:12:32)
- 4 (2008-01-25 (金) 14:01:40)
- 5 (2013-02-23 (土) 23:16:37)
- 6 (2013-10-17 (木) 15:02:04)
- 7 (2014-09-23 (火) 12:33:51)
- 8 (2014-10-10 (金) 01:33:19)
- 9 (2015-11-10 (火) 02:00:18)
- 10 (2017-05-09 (火) 17:55:36)
- 11 (2017-08-15 (火) 14:37:15)
- 12 (2018-05-30 (水) 20:54:09)
- 13 (2018-10-31 (水) 20:08:46)
- 14 (2020-10-31 (土) 00:20:29)
- 15 (2022-09-09 (金) 16:07:44)
- 16 (2024-02-02 (金) 11:41:01)
- 17 (2025-01-03 (金) 08:57:02)
- 18 (2025-01-03 (金) 09:01:23)
- 19 (2025-01-03 (金) 09:02:38)
- 20 (2025-01-03 (金) 09:03:21)
- 21 (2025-01-03 (金) 09:04:02)
- category: swing
folder: DockingConstraint
title: JToolBarのドッキングを上下のみに制限
tags: [JToolBar, BorderLayout]
author: aterai
pubdate: 2006-09-18T18:01:15+09:00
description: JToolBarのドッキングを上下のみに制限して、左右を無視するように設定します。
image:
概要
JToolBar
のドッキングを上下のみに制限して、左右を無視するように設定します。
Screenshot

Advertisement
サンプルコード
toolbar.setUI(new BasicToolBarUI() {
@Override public boolean canDock(Component c, Point p) {
return super.canDock(c, p) ? isHorizontalDockingConstraint(c, p) : false;
}
private boolean isHorizontalDockingConstraint(Component c, Point p) {
if (!c.contains(p)) return false;
int iv = toolBar.getOrientation() == JToolBar.HORIZONTAL
? toolBar.getSize().height
: toolBar.getSize().width;
if (p.x >= c.getWidth() - iv) {
return false;
} else if (p.x < iv) {
return false;
} else {
return true;
}
}
});
View in GitHub: Java, Kotlin解説
ToolBarUI#canDock(Component, Point)
メソッドをオーバーライドして左右の場合はfalse
を返すよう設定- このため
JToolBar
は上下にのみドッキング可能になるよう制限され、横長のJComboBox
などのコンポーネントを配置したJToolBar
が左右に配置されてレイアウトが崩れる心配がない
- このため
- ドッキングできるかどうかを判定している
BasicToolBarUI#getDockingConstraint
メソッドがprivate
のため、サンプルコードではこれをコピーしてすこしだけ条件を変更したisHorizontalDockingConstraint
メソッドを作成して使用 BorderLayout
のWEST
とEAST
に、たとえばサイズ0
のBox
や空のJLabel
などの適当な非表示コンポーネントを配置するとLookAndFeel
の変更なしでドッキングの制限が可能になるJPanel panel = new JPanel(new BorderLayout()); panel.add(toolbar, BorderLayout.NORTH); panel.add(Box.createRigidArea(new Dimension()), BorderLayout.WEST); panel.add(Box.createRigidArea(new Dimension()), BorderLayout.EAST);
参考リンク
BasicToolBarUI#canDock(...) (Java Platform SE 8)