简体   繁体   English

如何在JDialog上使用JTextArea时使关键事件起作用?

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

What I have basicly created is a JDialog which has a key event on the form. 我基本上创建的是JDialog,它在表单上有一个关键事件。 So when for example space is pressed it does something. 因此,当例如按下空间时,它会做一些事情。 This worked fine until I created a JTextArea on the same dialog, which is editable. 这工作正常,直到我在同一个可编辑的对话框上创建了一个JTextArea。 When I did this I can't remove the focus from the JTextArea and make the hot keys work. 当我这样做时,我无法从JTextArea中删除焦点并使热键工作。 How do I allow both the key events and the JTextArea to function on the same JDialog? 如何允许键事件和JTextArea在同一个JDialog上运行?

Let's assume you already have defined your KeyListener for your JDialog object. 假设您已经为JDialog对象定义了KeyListener

This is how you can get the components of a component: 这是您获取组件组件的方法:

dialog.getContentPane().getComponents();

This is how you can get the array of KeyListener s of your dialog : 这是你如何获得dialogKeyListener数组:

KeyListener[] keyListeners = dialog.getKeyListeners();

Now, let's iterate the Component s and add the KeyListener s: 现在,让我们迭代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]);
    }
}

Code is untested, if there are any typos, please, let me know. 代码未经测试,如有错别字,请告诉我。 Also, this is not transitive, that is, it does not dwelve into the listeners of the Component s of Component s, it defines the key events for the child Component s solely. 此外,这不是传递性的,也就是说,它不会停留在ComponentComponent的侦听器中,它仅为子Component定义了键事件。

What you need to do is add the KeyListener from the JDialog to the JTextArea . 您需要做的是将KeyListenerJDialog添加到JTextArea

Below is a SSCCE of this. 以下是对此的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());
            }
        };

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM