当 JDialog 上有 JTextArea 时,如何使按键事件在 JDialog 上工作?

How to make key events work on a JDialog while there is a JTextArea on it?

我基本上创建的是一个 JDialog,它在表单上有一个键事件。所以当按下 space 时,它会做一些事情。在我在同一个对话框上创建一个 JTextArea 之前,它工作得很好,它是可编辑的。当我这样做时,我无法将焦点从 JTextArea 上移开并使热键起作用。如何允许键事件和 JTextArea 在同一个 JDialog 上运行?

假设您已经为 JDialog 对象定义了 KeyListener

这是获取组件组件的方法:

dialog.getContentPane().getComponents();

这是获取 dialogKeyListener 数组的方法:

KeyListener[] keyListeners = dialog.getKeyListeners();

现在,让我们迭代 Component 并添加 KeyListener

Component[] components = dialog.getContentPane().getComponents();
KeyListener[] keyListeners = dialog.getKeyListeners();
for (int componentIndex = 0; componentIndex < components.length; componentIndex++) {
    for (int keyListenerIndex = 0; keyListenerIndex < keyListeners.length; keyListenerIndex++) {
        components[componentindex].addKeyListener(keyListeners[keyListenerIndex]);
    }
}

代码未经测试,如果有错别字,请告诉我。此外,这不是传递性的,也就是说,它不会进入 ComponentComponent 的侦听器,它只定义子 Component 的关键事件。

您需要做的是将 KeyListenerJDialog 添加到 JTextArea

下面是这个的 SSCCE。

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

public class DialogListener {

    public static void main(String[] args) {
        JDialog dialog = new JDialog();
        dialog.setSize(300, 400);
        dialog.setVisible(true);

        KeyListener listener = getKeyListener();

        dialog.addKeyListener(listener);

        JTextArea area = new JTextArea();
        area.addKeyListener(listener);

        dialog.add(area);
    }

    public static KeyListener getKeyListener(){
        return new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                System.out.println(e.getKeyChar());
            }
        };

    }
}