老是空指针异常,改了好些遍,都没成功,大家帮我看一下吧
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Demo extends JFrame {
MyJPanel myPanel;
public static void main(String[] args) {
Demo demo = new Demo();
}
public Demo(){
myPanel = new MyJPanel();
//System.out.println(myPanel);
this.add(myPanel);
MyListener listener = new MyListener(myPanel);
this.addKeyListener(listener);
this.setSize(400,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
class MyJPanel extends JPanel{
int x = 10;
int y = 10;
int speed = 1;
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void paint(Graphics g){
super.paint(g);
g.fillOval(x,y,10,10);
}
}
class MyListener implements KeyListener{
MyJPanel myPanel;
//此处报告空指针异常
int x = myPanel.getX();
int y = myPanel.getY();
int speed = myPanel.getSpeed();
public MyListener(){
}
public MyListener(MyJPanel myPanel){
this.myPanel = myPanel;
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W) {
myPanel.setY(y - speed);
} else if (e.getKeyCode() == KeyEvent.VK_S) {
myPanel.setY(y + speed);
} else if (e.getKeyCode() == KeyEvent.VK_A) {
myPanel.setX(x - speed);
} else if (e.getKeyCode() == KeyEvent.VK_D) {
myPanel.setX(x + speed);
}
myPanel.repaint();
}
public void keyReleased(KeyEvent e) {
}
}
备注那里为什么会出现空指针异常 求大神帮忙解决