2

我搜索了答案,但我发现的只是解决方法,而不是原因,所以我问这个问题:

我是 GUI 编程新手。在练习一些关于关键事件处理的代码时,我遇到了一个在 JFrame 中包含 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);
}
}
4

2 回答 2

2
于 2012-05-14T10:58:06.643 回答
2

这种行为的原因是JTextComponent处理KeyEvent. 正如 mKorbel 已经指出的那样,您应该使用 a DocumentListenerfor JTextComponents

于 2012-05-14T11:03:17.910 回答