• category: swing folder: RightPopupMenuComboBox title: JComboBoxのPopupMenuを右側に表示する tags: [JComboBox, JPopupMenu, PopupMenuListener, ArrowButton, Icon] author: aterai pubdate: 2010-03-22T02:10:46+09:00 description: JComboBoxの右側にPopupMenuが表示されるように設定します。 image: https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTR6-BHykI/AAAAAAAAAh8/0mx4AWajd58/s800/RightPopupMenuComboBox.png

概要

JComboBoxの右側にPopupMenuが表示されるように設定します。

サンプルコード

class RightPopupMenuListener implements PopupMenuListener {
  @Override public void popupMenuWillBecomeVisible(final PopupMenuEvent e) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() {
        JComboBox combo = (JComboBox) e.getSource();
        Accessible a = combo.getUI().getAccessibleChild(combo, 0);
        if (a instanceof BasicComboPopup) {
          BasicComboPopup pop = (BasicComboPopup) a;
          Point p = new Point(combo.getSize().width, 0);
          SwingUtilities.convertPointToScreen(p, combo);
          pop.setLocation(p);
        }
      }
    });
  }

  @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
    /* not needed */
  }

  @Override public void popupMenuCanceled(PopupMenuEvent e) {
    /* not needed */
  }
}
View in GitHub: Java, Kotlin

解説

  • JComboBoxのドロップダウンリストとしてPopupMenuが開くときにその表示位置を変更するPopupMenuListenerを作成
    • JComboBox#addPopupMenuListener(...)メソッドで追加
  • JComboBoxの矢印アイコンも、以下のように変更
    combo2.setUI(new WindowsComboBoxUI() {
      @Override protected JButton createArrowButton() {
        JButton button = new JButton(icon) {
          @Override public Dimension getPreferredSize() {
            return new Dimension(14, 14);
          }
        };
        button.setRolloverIcon(makeRolloverIcon(icon));
        button.setFocusPainted(false);
        button.setContentAreaFilled(false);
        return button;
      }
    });
    

参考リンク

コメント