我试图让每个对象JPanel
通过传递将自己绘制成 ,graphics
但我遇到了一个java.lang.NullPointerException
错误。
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
private static final long serialVersionUID = 1L;
Main panel;
Player mainPlayer;
public static void main(String[] args) {
JFrame frame = new JFrame("Asteroids");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Main panel = new Main();
frame.add(panel);
frame.setBackground(Color.BLACK);
frame.setSize(500, 400);
frame.setVisible(true);
}
public void paintComponent(Graphics g) {
mainPlayer.paintComponent(g);
}
}
然后这段代码在不同的 .java 文件中
import java.awt.Graphics;
public class Player {
public Player() {
}
public void paintComponent(Graphics g) {
}
}
有谁知道为什么这段代码不起作用?
它给了我:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Main.paintComponent(Main.java:23)