一、当java的命名与导入的类或模块起冲突的话,会导致很多异常问题出现。
二、代码(注意下方截图)
MainMethod.java:
package cn.lrt.program;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
class MainMethod extends Frame {
KeyListener keyListener = new KeyListener();
public void launchedFrame() {
this.setTitle("我是一个测试");
this.setVisible(true);
this.setSize(300,300);
this.setLocation(300,300);
this.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.addKeyListener(new KeyListener());
}
public static void main(String[] args) {
MainMethod method = new MainMethod();
method.launchedFrame();
}
class KeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
keyListener.addDirection(e);
}
public void keyReleased(KeyEvent e) {
}
}
}
KeyListener.java
package cn.lrt.program;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
class MainMethod extends Frame {
KeyListener keyListener = new KeyListener();
public void launchedFrame() {
this.setTitle("我是一个测试");
this.setVisible(true);
this.setSize(300,300);
this.setLocation(300,300);
this.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.addKeyListener(new KeyListener());
}
public static void main(String[] args) {
MainMethod method = new MainMethod();
method.launchedFrame();
}
class KeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
keyListener.addDirection(e);
}
public void keyReleased(KeyEvent e) {
}
}
}
三、错误截图
四、更改类名后(keyMonitorDemo.addDirection(e)不报错了)
五、错误原因
有可能是导入的类或继承的类中有了keyListener方法