如何同步两个JComboBox的弹出窗口可见性(comboBox和mirrorComboBox)

时间:2011-11-23 10:33:51

标签: swing jcombobox

我正在尝试同步两个组合框的弹出窗口 - 将它们称为comboBox和mirrorComboBox。 我想在弹出的comboBox变为可见时设置mirrorComboBox的弹出窗口。

我尝试通过将popupMenuListener添加到comboBox并在popupMenuWillBecomeVisible事件发生时调用mirrorComboBox.setPopupVisible(true)来实现此行为。它工作正常,但不幸的是它会导致另一个问题 - comboBox的弹出窗口永远不会被隐藏!事件弹出窗口一旦设置可见,就永远不会调用popupMenuWillBecomeInvisible方法。

如何同步两个组合框的弹出窗口可见性?

这是我的实施:

import java.awt.FlowLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

public class MirrorPopupsMainFrame extends JFrame implements PopupMenuListener {
    public static void main(String[] args) {
        new MirrorPopupsMainFrame().setVisible(true);
    }

    JComboBox comboBox;
    JComboBox mirrorComboBox;

    public MirrorPopupsMainFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        buildUi();
    }

    protected void buildUi() {
        String[] items = new String[]{"item1", "item2", "item3"};

        comboBox = new JComboBox(items);
        comboBox.addPopupMenuListener(this);

        mirrorComboBox = new JComboBox(items);

        setLayout(new FlowLayout());
        add(comboBox);
        add(mirrorComboBox);
        setBounds(0, 0, 300, 200);
    }

    @Override
    public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
        // Not calling the following line will cause
        // comboBox's popup to hide correctly.
        mirrorComboBox.setPopupVisible(true);
    }

    @Override
    public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
        mirrorComboBox.setPopupVisible(false);
    }

    @Override
    public void popupMenuCanceled(PopupMenuEvent e) {}

}

0 个答案:

没有答案