KeyEvent不适用于JTextArea,但适用于包含JTextArea的JFrame

时间:2012-05-14 10:56:27

标签: java swing jtextarea keylistener

我搜索了答案,但我找到的只是工作,而不是原因,所以我问这个问题:

我是GUI编程的新手。在练习一些关于键事件处理的代码时,我遇到了一个JFxt中包含JTextArea的示例。 keylistener接口由Frame本身实现。按下某个键时,根据按下的键,文本区域会显示一些相关信息。代码工作正常。

但我尝试以不同的方式尝试将JTextarea注册到keyListenr而不是JFrame。但是,这不会对关键事件做出响应。这是下面的代码。请帮忙。

public class KeyDemoFrame extends JFrame
{
private String line1 = "";
private String line2 = "";
private String line3 = "";
private JTextArea textArea;

public KeyDemoFrame()
{
    super("Demonstrating Keystrong events");
    textArea = new JTextArea(10,21);
    textArea.setText("Press any key on keyboard");
    textArea.setEnabled(false);
    textArea.setDisabledTextColor(Color.BLACK);
    add(textArea);
    //addKeyListener( this );

    KeyEventHandler keyStrokeHandler = new KeyEventHandler();
    addKeyListener(keyStrokeHandler);
}   
    private class KeyEventHandler implements KeyListener
    {
        public void keyPressed(KeyEvent event)
        {
            line1 = String.format("Your pressed the %s key", KeyEvent.getKeyText(event.getKeyCode()));
            setLines2and3(event);

        }
        public void keyReleased(KeyEvent event)
        {
            line1 = String.format("You released %s key", KeyEvent.getKeyText(event.getKeyCode()));
            setLines2and3(event);
        }
        public void keyTyped(KeyEvent event)
        {
            line1 = String.format("You typed %s key",KeyEvent.getKeyText(event.getKeyCode()));
            setLines2and3(event);
        }
        private void setLines2and3(KeyEvent event)
        {
            line2 = String.format("This key is %san action key", (event.isActionKey()?"":"not "));
            String temp = KeyEvent.getKeyModifiersText( event.getModifiers() );
            line3 = String.format( "Modifier keys pressed: %s",( temp.equals( "" ) ? "none" : temp ) );
            textArea.setText( String.format( "%s\n%s\n%s\n",line1, line2, line3 ) );
        }
    }

}

import javax.swing.JFrame;

public class KeyDemo
{
public static void main(String[] args)
{
    KeyDemoFrame keyDemoFrame = new KeyDemoFrame();
    keyDemoFrame.setSize(300, 100);
    keyDemoFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    keyDemoFrame.setVisible(true);
}
}

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:2)

此行为的原因是JTextComponent处理KeyEvent。正如mKorbel已经指出你应该使用DocumentListener JTextComponent s