[英]KeyEvent not functioning for JTextArea, but works for the JFrame containing the JTextArea
我搜索了答案,但是我發現的只是解決方法,而不是原因,所以我問這個問題:
我是GUI編程的新手。 在練習一些有關鍵事件處理的代碼時,我遇到了一個JFrame內包含JTextArea的示例。 偵聽器接口由框架本身實現。 當按下某個鍵時,基於按下的鍵,一些相關信息會顯示在文本區域中。 該代碼工作正常。
但我嘗試另辟and徑,並嘗試將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);
}
}
出現這種情況的原因是JTextComponent
處理KeyEvent
。 正如mKorbel已經指出的那樣,您應該對JTextComponent
使用DocumentListener
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.