0

我有一个具有自定义摆动组件和 JTextfield 和 JButton 的 JFrame。JButton 已设置为默认按钮。当我在文本字段处于焦点的那一刻按 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 方法,因为它在自定义组件中执行特殊事件。当我在自定义组件的焦点时刻按下回车键时,我应该怎么做才能触发按钮?

4

1 回答 1

0

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

super.processKeyEvent(event);
于 2013-10-16T05:15:17.037 回答