Swing/MenuItemTextAlignment のバックアップ(No.20)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/MenuItemTextAlignment へ行く。
- 1 (2016-07-18 (月) 01:56:46)
- 2 (2016-12-16 (金) 20:00:58)
- 3 (2017-04-07 (金) 13:51:51)
- 4 (2017-08-01 (火) 21:55:51)
- 5 (2017-08-15 (火) 14:19:35)
- 6 (2018-08-17 (金) 13:32:45)
- 7 (2019-02-25 (月) 17:43:48)
- 8 (2020-12-10 (木) 12:11:31)
- 9 (2021-05-12 (水) 07:29:38)
- 10 (2022-08-20 (土) 22:15:25)
- 11 (2023-10-05 (木) 11:59:50)
- 12 (2023-10-16 (月) 12:37:08)
- 13 (2025-01-03 (金) 08:57:02)
- 14 (2025-01-03 (金) 09:01:23)
- 15 (2025-01-03 (金) 09:02:38)
- 16 (2025-01-03 (金) 09:03:21)
- 17 (2025-01-03 (金) 09:04:02)
- 18 (2025-06-19 (木) 12:41:37)
- 19 (2025-06-19 (木) 12:43:47)
- 20 (2025-10-27 (月) 06:48:05)
- category: swing
folder: MenuItemTextAlignment
title: JMenuに追加したJMenuItemなどのテキスト位置を揃える
tags: [JMenuBar, JMenu, JMenuItem, LookAndFeel]
author: aterai
pubdate: 2016-07-18T01:53:49+09:00
description: JMenuに追加したJMenuItemやJLabelなどのコンポーネントのテキスト位置を揃えて表示します。
image:

Summary
JMenuに追加したJMenuItemやJLabelなどのコンポーネントのテキスト位置を揃えて表示します。
Screenshot

Advertisement
Source Code Examples
// U+200B zero width space
JMenuItem item3 = new JMenuItem("\u200B"); //, HSTRUT);
// item3.setLayout(new BorderLayout());
// item3.setBorder(BorderFactory.createEmptyBorder()); // NimbusLookAndFeel
item3.setEnabled(false);
// item3.setDisabledIcon(HSTRUT);
item3.add(new JMenuItem("JMenuItem(disabled) with JMenuItem", HSTRUT) {
@Override public boolean contains(int x, int y) {
return false; // disable mouse events
}
});
View in GitHub: Java, KotlinDescription
JMenuやJPopupMenuにクリック不可の項目としてJMenuItemの代わりにJLabelを追加すると、WindowsLookAndFeelを使用している場合や他のJMenuItemにアイコンが設定されている場合にテキストの開始位置が揃わないので、これを回避するために以下の方法をテストしています。
JMenuItem.setEnabled(false);JMenuItem.setEnabled(false);とUIManager.put("MenuItem.disabledForeground", Color.BLACK);を使用MenuItem.disabledForegroundが使用されるかどうかはLookAndFeelに依存
JLabel + EmptyBorder- 余白を設定した
JLabelを使用 - 余白の幅は
LookAndFeelに依存(LookAndFeel依存の幅を取得する方法がない?)
- 余白を設定した
JPanel with JMenuItemMenuElementではない透明なJPanelにJComponent#contains()メソッドをオーバーライドしてマウスクリックを無効にしたJMenuItemを追加
JMenuItem(disabled) with JMenuItemJMenuItem.setEnabled(false);とした空のJMenuItemにJComponent#contains()メソッドをオーバーライドしてマウスクリックを無効にしたJMenuItemを追加
JMenuにアイコン用の余白がないMetalLookAndFeelなどにアイコンが設定されたJMenuItemが存在する場合、幅のみのアイコンを設定する必要があるMetalLookAndFeelの場合、文字列もアイコンも存在しないJMenuItemは他のJMenuItemと高さが異なる(幅ゼロ空白文字\u200Bで回避)NimbusLookAndFeelのJPanelは、デフォルトでは背景が不透明
Reference
- java - JLabel with icon in JPopupMenu doesn't follow other JMenuItem alignment - Stack Overflow
- JDK-8152981 Double icons with JMenuItem setHorizontalTextPosition on Win 10 - Java Bug System
- JCheckBoxMenuItemのチェックアイコンの位置を調整する
Java 8からCheckBoxMenuItem.afterCheckIconGapやCheckBoxMenuItem.minimumTextOffsetなどが追加されているため、揃えやすくなった