处理action仅在用户确认选择时才在JComboBox上执行

时间:2011-11-09 21:38:51

标签: java swing search keyboard jcombobox

当我在不可编辑的JComboBox上注册ActionListener时,每当用户使用箭头键或上下文搜索(键入项目名称的第一个字母)更改所选项目时,它就会触发actionPerformed()。

我在这里发现了类似的问题: How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard。但该解决方案不包括上下文搜索选项。当我输入内容时它会触发actionPerformed()。

如何确定用户何时使用回车键或鼠标点击确认所选项目?

2 个答案:

答案 0 :(得分:7)

更好的是实现ItemListener(被激活两次SELECTED和DESELECTED),而不是ActionListenerKeyBindings,也许是成功的这个简单示例here

import java.awt.*;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

public class PopupTest {

    public static void main(String[] args) {
        final JComboBox c = new JComboBox();
        c.addPopupMenuListener(new PopupMenuListener() {

            @Override
            public void popupMenuCanceled(PopupMenuEvent e) {
                System.out.println(e.getSource());
            }

            @Override
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                System.out.println(e.getSource());
            }

            @Override
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                System.out.println(e.getSource());
            }
        });
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().setLayout(new FlowLayout());
        f.getContentPane().add(c);
        f.pack();
        f.setVisible(true);
    }

    private PopupTest() {
    }
}

答案 1 :(得分:3)

谢谢你的回答。这就是我真正需要的。 当弹出窗口不可见时,当用户使用箭头键移动组合框时,我还添加了actionListener:

scriptsCombobox.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        JComboBox source = (JComboBox) e.getSource();
        if(!source.isPopupVisible()){
            //update data
        }
    }
});