我正在学习Java编程,并且正在尝试从书中编译以下代码。当我尝试编译代码时,我收到此错误
Keystrokes is not abstract and does not override abstract method
keyTyped (java.awt.event.KeyEvent) in java.awt.event.KeyListener.
另外,我认为这是不相关的,但是本书还告诉我将这部分代码添加到源代码中(某处?):
pnl.add ( field) ;
pnl.add (txtArea);
当我这样做时,我得到一个标识符“预期错误”。
程序代码:
import javax.swing.*;
import java.awt.event.*;
class Keystrokes extends JFrame implements KeyListener
{
JPanel pnl = new JPanel();
public static void main (String[ ] args){
Keystrokes gui = new Keystrokes();
}
JTextField field = new JTextField ( 38 );
JTextArea txtArea = new JTextArea (5, 38);
public Keystrokes()
{
super( "Swing window");
setSize( 500,200);
setDefaultCloseOperation( EXIT_ON_CLOSE );
add(pnl);
field.addKeyListener (this );
setVisible( true );
}
public void keyPressed(KeyEvent event )
{
txtArea.setText("Key Pressed");
throw new UnsupportedOperationException("Not supported yet.");
}
public void KeyTyped (KeyEvent event ) {
throw new UnsupportedOperationException("Not supported yet.");
txtArea.append("\nCharacter : " + event.getKeyChar() );
}
public void keyReleased ( KeyEvent event)
{
int keyCode = event.getKeyCode();
txtArea.append("\nKey Code : " + event.getKeyCode() );
textArea.append("\nKey Text : " + event.getKeyText(keyCode));
}
}
答案 0 :(得分:3)
您的方法KeyTyped
应为keyTyped
。资本化很重要。
答案 1 :(得分:1)
Keystrokes is not abstract and does not override abstract method keyTyped (java.awt.event.KeyEvent) in java.awt.event.KeyListener.
这意味着您的KeyListener
类声称要实现的Keystrokes
接口有一些必须实现的其他方法,但您没有这样做。实现keyTyped
方法并查看javadoc以查看是否遗漏了其他人。
这应该可以帮到你解决下一个问题。
答案 2 :(得分:1)
Java区分大小写;您将方法命名为KeyTyped而不是基类中所需的keyTyped。