【问题标题】:Close custom dialog when Enter is pressed in input field在输入字段中按下 Enter 时关闭自定义对话框
【发布时间】:2015-09-10 11:30:40
【问题描述】:

我设计了(使用 Netbeans 中的 GUI 设计器)一个带有两个单选按钮和一个数字微调器的小对话框。

  1. 如果我在焦点位于其中一个单选按钮上时按 Enter,对话框会正确关闭,但如果焦点位于微调器上,我必须使用 Tab 离开它才能使用 Enter 键。
    1. 如何指示对话框 Enter 的真正含义是“接受并关闭”?
    2. 或者,我如何指示(每个)输入字段将 Enter 中继到“接受并关闭”处理程序?
    3. 同样,即使焦点位于微调器(或其他字段)上,如何指示对话框 Esc 的真正含义是“取消并关闭”?

【问题讨论】:

  • 你有什么问题?
  • 我在输入关键字时按了回车键,不小心发布了没有问题的问题。对不起!
  • @KlaymenDK 在此处搜索由键绑定标记的问题
  • If I press Enter while the focus is on one of the radio buttons, the dialog correctly closes - 那么你是怎么做到的呢?您是否使用 KeyListener、Key Bindings 或其他方法。我们无法猜测您的代码当前正在做什么,因此我们无法建议您可能做错了什么。当您提出问题时,请发布适当的 SSCCE 来说明问题,这样我们就不必猜测您可能在做什么,也可能不做什么。
  • 那我是怎么做到的?很抱歉,我不知道,除了我使用了 Netbeans GUI 编辑器。我对摇摆相当陌生,对 Netbeans 也是全新的,所以“谁知道”(不是我)它是如何连接的。不过我正在学习!

标签: java swing netbeans input dialog


【解决方案1】:

我怀疑我遇到问题的原因是 微调器实际上是一个复合控件,而文本(嗯,数字)字段是其中的一个组成部分。所以我需要将事件连接到那个子组件,而不是连接到微调器本身:

// Make Ok/Cancel work when JSpinner has focus
    getSpinnerField(jSpinnerOffset).addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            doOk();
        }
    });

其中“getSpinnerField()”只是私有方法中的简写:

private JFormattedTextField getSpinnerField(JSpinner spinner) {
    return ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField();
}

执行此操作后,Esc 键会自动关闭对话框。

【讨论】:

    【解决方案2】:

    如何指示(每个)输入字段将 Enter 中继到“接受并关闭”处理程序?

    最简单的方法是在对话框上定义一个“默认按钮”。然后,当按下 Enter 时,将激活默认按钮。查看 Enter Key 和 Button 了解执行此操作的不同方法。

    如何指示对话框 Esc 真正的意思是“取消并关闭”

    使用Key Bindings 调用取消按钮的操作。

    首先您定义一个供按钮使用的Action

    public class CancelAction extends AbstractAction
    {
        public CancelAction()
        {
            super("Cancel");
            putValue( Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_C) );
        }
    
        @Override
        public void actionPerformed(ActionEvent e)
        {
            Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
    
            if (window != null)
            {
                WindowEvent windowClosing = new WindowEvent(window, WindowEvent.WINDOW_CLOSING);
                window.dispatchEvent(windowClosing);
            }
        }
    }
    

    然后将Action 添加到按钮上,以便用户可以使用鼠标:

    CancelAction cancelAction = new CancelAction();
    cancelButton.setAction( cancelAction );
    dialog.add(cancelButton);
    

    现在您可以使用 Key Bindings 将 Escape 键绑定到 CancelAction,以便用户可以使用键盘:

    KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
    getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "ESCAPE");
    getRootPane().getActionMap().put("ESCAPE", cancelAction);
    

    【讨论】:

      猜你喜欢
      • 2012-05-06
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      相关资源
      最近更新 更多