Swing/RightPopupMenuComboBox のバックアップの現在との差分(No.1)
TITLE:JComboBoxのPopupMenuを右側に表示する
Posted by terai at 2010-03-22
JComboBoxのPopupMenuを右側に表示する
JComboBoxの右側にPopupMenuが表示されるように設定します。- 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:
概要
JComboBox
の右側にPopupMenu
が表示されるように設定します。
- &jnlp;
- &jar;
- &zip;
Screenshot
Advertisement
#screenshot
サンプルコード
#spanend
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#spanend
class RightPopupMenuListener implements PopupMenuListener {
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
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 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);
}
});
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
public void popupMenuCanceled(PopupMenuEvent e) {}
#spanadd
#spanend
@Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
/* not needed */
}
#spanadd
#spanend
@Override public void popupMenuCanceled(PopupMenuEvent e) {
/* not needed */
}
}
解説
上記のサンプルでは、JComboBoxのPopupMenuが開くときに、その位置を変更するようなPopupMenuListenerを作成し、addPopupMenuListenerメソッドで追加しています。- - JComboBoxの矢印アイコンも、以下のようにして変更しています。
解説
-
JComboBox
のドロップダウンリストとしてPopupMenu
が開くときにその表示位置を変更するPopupMenuListener
を作成-
JComboBox#addPopupMenuListener(...)
メソッドで追加
-
-
JComboBox
の矢印アイコンも以下のように変更#spandel combo2.setUI(new com.sun.java.swing.plaf.windows.WindowsComboBoxUI() { #spanend protected JButton createArrowButton() { #spanadd combo2.setUI(new WindowsComboBoxUI() { #spanend @Override protected JButton createArrowButton() { JButton button = new JButton(icon) { public Dimension getPreferredSize() { @Override public Dimension getPreferredSize() { return new Dimension(14, 14); } }; button.setRolloverIcon(makeRolloverIcon(icon)); button.setFocusPainted(false); button.setContentAreaFilled(false); return button; } });