【问题标题】:JComboBox take priority before Keyboard shortcutJComboBox 优先于键盘快捷键
【发布时间】:2018-03-17 10:58:26
【问题描述】:

我在 java 中添加了一些键盘快捷键,并且大部分时间它们都按预期工作。 仅当焦点在组合框内,并且组合框包含以快捷方式开头的值时,然后按该键更改组合框值,而不运行操作。

在以下示例中,我希望按下 1/2 将始终调用 button1/button2,但它正在更改组合中的值。

有什么简单的方法可以改变这种行为吗?

+注意,我尝试在函数 registerKeyboardAction 中设置 3 参数 而是:

JComponent.WHEN_IN_FOCUSED_WINDOW

到:

JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT

这没有帮助。

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class TestCombo {

    public static void main(String[] args) {

        JFrame frame = new JFrame("TEST");

        JPanel panel = new JPanel();

        JComboBox<String> comboBox = new JComboBox<String>(new String[]{"1", "2", "3", "4", "5"});

        panel.add(comboBox);

        JButton button1 = new JButton(new TextAction("Text1"));
        JButton button2 = new JButton(new TextAction("Text2"));

        panel.add(button1);
        panel.add(button2);

        panel.registerKeyboardAction(button1.getAction(), KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, false), JComponent.WHEN_IN_FOCUSED_WINDOW);
        panel.registerKeyboardAction(button2.getAction(), KeyStroke.getKeyStroke(KeyEvent.VK_2, 0, false), JComponent.WHEN_IN_FOCUSED_WINDOW);

        frame.add(panel);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(400, 200));
        frame.pack();
        frame.setVisible(true);

    }


    private static class TextAction extends AbstractAction{

        private String text;

        public TextAction(String vText){
            text = vText;
            putValue(Action.NAME, text);
        }


        @Override
        public void actionPerformed(ActionEvent arg0) {
            JOptionPane.showMessageDialog(null, text);
        }


    }
}

【问题讨论】:

    标签: jcombobox shortcut


    【解决方案1】:

    我搜索了其他帖子,目前没有找到最佳解决方案,但作为解决方法,我找到了在组合框值中添加一些前缀的选项(例如,每个值前的空格)。这样,快捷方式就起作用了。当然,问题是您将无法使用键来搜索组合框值。但就我而言,这正是我想要的。

    JComboBox<String> comboBox = new JComboBox<String>(new String[]{" 1", " 2", " 3", " 4", " 5"});
    

    【讨论】:

      猜你喜欢
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多