为什么从其他 class 调用 JPanel 会出现 NullPointerException 错误?

Why does calling a JPanel from other class give NullPointerException error?

我是 Java GUI 的新手,我正在尝试制作我的第一个视觉效果 game.A window,包括当我们 运行程序,如果你点击其中一个,游戏 starts.At 首先,我创建了一个 class 扩展 JPanel 所以我的第一个面板将被创建,我将创建一个对象 class 并将其添加到 JFrame.But 我需要在单击按钮时更改面板,因此我在主游戏 class 中创建了一个新的 JPanel 对象 JPanel。 因为第二个 JPanel 是以不同的方式创建的,所以我将我的第一个 JPanel 变成了一个类似的 JPanel 并将 getter 和 setter 放入我的框架 class.But 代码给我 NullPointerException 错误。

这是我的 classes:

public class Frame {
 
 //The constructor method for frame.
 
 private static JPanel panel;
 
 public Frame () {
  
  JFrame frame = new JFrame();
  
  frame.add(panel);    //Adding the panel of the game to the frame.
  frame.setTitle("Halma Game");       //The title of the window popped up when the program runs.
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.pack();
  frame.setVisible(true);
 }

 public static JPanel getPanel() {
  return panel;
 }

 public static void setPanel(JPanel panel) {
  Frame.panel = panel;
 }

}

public class MenuPanel extends JPanel implements ActionListener {
 
 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 
 
 private JButton playButton;
 private JButton recordButton;
    private JLabel label;
    private JPanel panel = new JPanel();

 public MenuPanel() {
  
  panel.setBorder(BorderFactory.createEmptyBorder(300,400,300,400));
  panel.setLayout(new GridLayout(0,1));
  panel.setBackground(Color.decode("255128255"));
  
     playButton = new JButton("New Game");
     playButton.setFocusable(false);
     playButton.setBackground(Color.PINK);
     playButton.setFont(new Font("Ariel",Font.ITALIC,25));
  playButton.addActionListener(this); //???     //Mohreha ro ye abstact beheshon bezani khoobe
  panel.add(playButton);
  
  recordButton = new JButton("HighScores");
  recordButton.setFocusable(false);
  recordButton.setBackground(Color.pink);
  playButton.setFont(new Font("Ariel",Font.ITALIC,25));
  panel.add(recordButton);
  label = new JLabel();
  
 }


 @Override
 public void actionPerformed(ActionEvent e) {
  GamePanel game = new GamePanel();
  game.start();
  
 }
 
  
  
  

}

我还没有在此代码上尝试过第二个 JPanel,但这个似乎不起作用。

嗨,埃琳娜,您的面板尚未实例化

私有静态 JPanel 面板;

当你打电话时

frame.add(面板); //将游戏的面板添加到框架中。