我用的是myeclipse 为什么一加红色字部分的代码,就报错?
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class KeyEventDemo {
private Frame f;
private TextField tf;
KeyEventDemo(){
init();
}
public void init(){
f=new Frame("MyFrame");
TextField tf=new TextField(50);
f.setBounds(300, 100, 600, 400);
f.setLayout(new FlowLayout());
f.add(tf);
myEvent();
f.setVisible(true);
}
public void myEvent(){
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
super.windowClosing(e);
System.exit(0);
}
});
tf.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int code=e.getKeyCode();
if(!(code>=KeyEvent.VK_0&&code<=KeyEvent.VK_9)){
System.out.println("非法");
}
}
});
}
public static void main(String[] args) {
new KeyEventDemo();
}
} |