JMenuに追加したJMenuItemなどのテキスト位置を揃える
Total: 4290, Today: 1, Yesterday: 0
Posted by aterai at
Last-modified:
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
- [JDK-8370465] Right to Left Orientation Issues with MenuItem Component. - Java Bug System
- JCheckBoxMenuItemのチェックアイコンの位置を調整する
Java 8からCheckBoxMenuItem.afterCheckIconGapやCheckBoxMenuItem.minimumTextOffsetなどが追加されているため、揃えやすくなった