如果使用自定义弹出窗口,为什么组合框不起作用?

时间:2014-01-26 22:14:06

标签: java swing jcombobox jpopupmenu

我正在尝试将弹出菜单的UI替换为菜单角正确舍入的UI。外观方面看起来一切正常,但我注意到在使用组合框时,选择菜单项时实际上并没有选择该选项。就像窗口在处理鼠标按下事件之前消失一样。

有趣的是,如果您按住鼠标并将其释放到所需选项上,它会注册该事件。键盘导航也可以正常工作。

在调试器中,我能够看到postEvent()MOUSE_PRESSED事件调用,但无法确定它之后的位置。 MOUSE_RELEASED是应该实际触发选择项目的内容,但我根本看不到其中一个被触发。

我将我的代码缩减为更简单的版本(没有所有渲染内容)仍然会导致问题。

如果您移除了对我自定义用户界面中设置的UIManager.put的调用,则一切正常。

PopupMenuTest.java:

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;

public class PopupMenuTest implements Runnable {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new PopupMenuTest());
    }

    @Override
    public void run() {
        UIManager.put("PopupMenuUI", CustomPopupMenuUI.class.getName());

        JComboBox<String> comboBox = new JComboBox<>(new String[] {
            "Apples", "Bananas", "Cantaloupes" });

        JFrame frame = new JFrame("Test");
        frame.setLayout(new BorderLayout());
        frame.add(comboBox, BorderLayout.CENTER);
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

CustomPopupMenuUI.java:

import javax.swing.JComponent;
import javax.swing.JPopupMenu;
import javax.swing.JWindow;
import javax.swing.Popup;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicPopupMenuUI;

public class CustomPopupMenuUI extends BasicPopupMenuUI {
    @SuppressWarnings("UnusedDeclaration") // called via reflection
    public static ComponentUI createUI(JComponent component) {
        return new CustomPopupMenuUI();
    }

    @Override
    public Popup getPopup(JPopupMenu popupMenu, int x, int y) {
        return new CustomPopup(popupMenu, x, y);
    }

    private static class CustomPopup extends Popup {
        private final JWindow popupWindow;

        CustomPopup(JPopupMenu popupMenu, int ownerX, int ownerY) {
            this.popupWindow = new JWindow();
            popupWindow.setContentPane(popupMenu);
            popupWindow.setLocation(ownerX, ownerY);
        }

        @Override
        public void show() {
            this.popupWindow.pack();
            this.popupWindow.setVisible(true);
        }

        @Override
        public void hide() {
            this.popupWindow.setVisible(false);
            this.popupWindow.removeAll();
            this.popupWindow.dispose();
        }
    }
}

0 个答案:

没有答案