Swing/MenuLocation のバックアップ(No.1)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/MenuLocation へ行く。
- category: swing folder: MenuLocation title: JMenuから開くJPopupMenuの位置を変更する tags: [JMenu, JPopupMenu] author: aterai pubdate: 2021-03-29T01:29:30+09:00 description: JMenuを選択して開くJPopupMenuが親ウィンドウ内に表示されるよう位置を変更します。 image: https://drive.google.com/uc?id=1Q6GqbhFRGHceMYa29cpE4fGNEfOwcA05
概要
JMenuを選択して開くJPopupMenuが親ウィンドウ内に表示されるよう位置を変更します。
Screenshot

Advertisement
サンプルコード
JMenu menu = new JMenu(key) {
@Override public void setPopupMenuVisible(boolean b) {
if (isTopLevelMenu()) {
Point p = getLocation();
Rectangle r = getRootPane().getBounds();
Dimension d1 = getPopupMenu().getPreferredSize();
if (p.x + d1.width > r.width) {
Dimension d2 = getPreferredSize();
setMenuLocation(d2.width - d1.width, d2.height);
}
}
super.setPopupMenuVisible(b);
}
};
View in GitHub: Java, Kotlin解説
JMenuがJMenuBarに配置されたTopLevelMenuでJMenuを選択して表示されるJPopupMenuが親Window領域外に配置される場合、オーバーライドしたJMenu#setPopupMenuVisible(...)内でJMenu#setMenuLocation(...)を使用して親Window領域内に収まるようJPopupMenuの位置を変更TopLevelMenuの場合のJPopupMenuの表示位置オフセットはUIManager.put("Menu.menuPopupOffsetX", offset)、UIManager.put("Menu.menuPopupOffsetY", offset)で変更可能TopLevelMenuではない場合のJPopupMenuの表示位置オフセットはUIManager.put("Menu.submenuPopupOffsetX", offset)、UIManager.put("Menu.submenuPopupOffsetY", offset)で変更可能JMenuがTopLevelMenuではなくサブメニューの場合、同じくオーバーライドしたJMenu#setPopupMenuVisible(...)内でJMenu#setMenuLocation(...)を使用して親JPopupMenuと同じ位置に同じサイズでJPopupMenuを表示するようその位置を変更WindowsLookAndFeelの場合親JPopupMenuのハイライトが手前に残る場合がある?- テストとして
JMenu内にカーソルが入ったときではなくクリックイベントでJPopupMenuを開閉するようJMenu#setDelay(...)に100秒の遅延時間を設定しているがおそらく修正が必要になりそう
JMenu menu = new JMenu(title) {
@Override public void setPopupMenuVisible(boolean b) {
JPopupMenu popup = getPopupMenu();
popup.setPopupSize(getParent().getPreferredSize());
Point p = getLocation();
setMenuLocation(-p.x, -p.y);
super.setPopupMenuVisible(b);
}
@Override public JMenuItem add(JMenuItem item) {
item.setMaximumSize(new Dimension(Short.MAX_VALUE, item.getPreferredSize().height));
return super.add(item);
}
};