JComboBoxのPopupMenuを右側に表示する
Total: 6492
, Today: 1
, Yesterday: 0
Posted by aterai at
Last-modified:
概要
JComboBox
の右側にPopupMenu
が表示されるように設定します。
Screenshot
Advertisement
サンプルコード
class RightPopupMenuListener implements PopupMenuListener {
@Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
EventQueue.invokeLater(() -> {
JComboBox<?> combo = (JComboBox<?>) e.getSource();
Accessible a = combo.getAccessibleContext().getAccessibleChild(0);
// Or Accessible a = combo.getUI().getAccessibleChild(combo, 0);
if (a instanceof JPopupMenu) {
JPopupMenu pop = (JPopupMenu) 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; } });