【问题标题】:default button is not listen to enter key when focus in custom component当焦点在自定义组件中时,默认按钮不听输入键
【发布时间】:2013-10-15 14:11:48
【问题描述】:

我有一个 JFrame,它有自定义的 swing 组件以及 JTextfield 和 JButton。 JButton 已设置为默认按钮。当我在文本字段处于焦点的那一刻按 Enter 键时,按钮将触发。但是当我在焦点按钮中的自定义组件不会触发的那一刻按 Enter 键时。

package org.laki.test;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.FlowLayout;
import javax.swing.JComboBox;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

public class TestFrame extends JFrame {
private JTextField textField;
public TestFrame() {
    getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

    textField = new JTextField();
    getContentPane().add(textField);
    textField.setColumns(10);

    ComboBox comboBox = new ComboBox();
    comboBox.addItem("lakshman");
    comboBox.addItem("tharindu");
    comboBox.addItem("Ishara");
    getContentPane().add(comboBox);

    JButton btnNewButton = new JButton("Test");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            System.out.println("enter is hitting...!!!");
        }
    });
    getContentPane().add(btnNewButton);
    this.rootPane.setDefaultButton(btnNewButton);
}

private class ComboBox extends JComboBox<String>
{
  private static final long serialVersionUID = 10000012219553L;

  @Override
  public void processKeyEvent(final KeyEvent event)
  {
    if ((event.getKeyCode() == KeyEvent.VK_DOWN) ||
        (event.getKeyCode() == KeyEvent.VK_SPACE))
    {
             doSomthing();
    }
    else if(event.getKeyCode() == KeyEvent.VK_ENTER)
    {
        //I added this to capture the enter event
    }
  }
}
public static void main(String[] args) {
    TestFrame testframe = new TestFrame();
    testframe.setSize(300, 400);
    testframe.setVisible(true);
}

 }

我无法删除 processKeyEvent 方法,因为它在自定义组件中执行特殊事件。 当我在自定义组件的焦点时刻按下回车键时,我应该怎么做才能触发按钮?

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖SSCCE
  • 并添加说明您这样做的原因
  • @mKorbel:我想在我的 JFrame 中保留一个默认按钮。但是当焦点放在 ComboBox 上时,当我点击进入默认按钮时不会触发。
  • 错了,不是,(即使我在这里发布如何做和覆盖所有内容)使用 ListSelectionListener,所有事件都在一个地方

标签: java swing focus custom-component


【解决方案1】:

您的自定义组件可能已覆盖 JComponent.processKeyEvent() 并且不允许调用它的父级实现。检查,如果没有,则使用

将关键事件传递给父级
super.processKeyEvent(event);

【讨论】:

    猜你喜欢
    • 2012-02-05
    • 2013-05-14
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多