Swing/PopupMenuWidth のバックアップ(No.8)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/PopupMenuWidth へ行く。
- 1 (2017-07-17 (月) 23:31:20)
- 2 (2018-02-15 (木) 14:23:42)
- 3 (2018-07-14 (土) 18:56:42)
- 4 (2020-07-07 (火) 14:22:33)
- 5 (2021-12-10 (金) 15:38:48)
- 6 (2023-03-20 (月) 18:49:22)
- 7 (2025-01-03 (金) 08:57:02)
- 8 (2025-01-03 (金) 09:01:23)
- 9 (2025-01-03 (金) 09:02:38)
- 10 (2025-01-03 (金) 09:03:21)
- 11 (2025-01-03 (金) 09:04:02)
- category: swing folder: PopupMenuWidth title: JPopupMenuの最小幅を設定する tags: [JPopupMenu, JMenu, JMenuItem, LayoutManager] author: aterai pubdate: 2017-07-17T23:29:21+09:00 description: JPopupMenuに下限となる最小幅を固定値で設定します。 image: https://drive.google.com/uc?id=1SYHBxJoZ2kPCmF9HQVhg0esnQTnpSZpq5w
Summary
JPopupMenu
に下限となる最小幅を固定値で設定します。
Screenshot

Advertisement
サンプルコード
menu = new JMenu("BoxHStrut");
menu.add(Box.createHorizontalStrut(200));
View in GitHub: Java, Kotlin解説
Default
JMenu
に配置されたコンポーネントの最も大きな推奨サイズの幅からJPopupMenu
の幅が決まる
BoxHStrut
Box.createHorizontalStrut(...)
で高さ0
で任意の幅(このサンプルでは200
)のコンポーネントを作成してJMenu
に配置- この
Box
の幅がJPopupMenu
の最小幅になる - この
Box
はMenuElement
インタフェースに適合しないのでJMenu#getSubElements()
の戻り値には含まれない
Override
JMenu
に配置するJMenuItem
のgetPreferredSize()
メソッドをオーバーライドして任意の幅を返すように設定- この
JMenuItem
の幅がJPopupMenu
の最小幅になる
Layout
JMenu
が使用するJPopupMenu
のレイアウトを変更DefaultMenuLayout#preferredLayoutSize(...)
メソッドをオーバーライドして任意の幅を返すように設定popup.setLayout(new DefaultMenuLayout(popup, BoxLayout.Y_AXIS) { @Override public Dimension preferredLayoutSize(Container target) { Dimension d = super.preferredLayoutSize(target); d.width = Math.max(200, d.width); return d; } });
Html
- 余白などを
0
にし、幅を設定した<table>
タグで装飾した文字列を使用するJMenuItem
を使用new JMenuItem("<html><table cellpadding='0' cellspacing='0' style='width:200'>...")
- 文字列自体の幅が
<table>
で指定した幅になるのでAccelerator
などが存在するとその幅も追加される html
タグを使用するのでMnemonic
が表示できない
- 余白などを