【问题标题】:Why does calling a JPanel from other class give NullPointerException error?为什么从其他类调用 JPanel 会给出 NullPointerException 错误?
【发布时间】:2020-06-13 15:44:02
【问题描述】:

我是Java GUI的新手,我正在尝试制作我的第一个视觉游戏。当我们运行程序时会弹出一个包含两个按钮的窗口,如果你点击其中一个按钮,游戏就会开始。在首先,我创建了一个扩展 JPanel 的类,因此将创建我的第一个面板,我将创建该类的一个对象并将其添加到 JFrame。但是我需要在单击按钮时更改面板,所以我创建了一个我的主游戏类中的新 JPanel 对象 JPanel。 因为第二个 JPanel 是以不同的方式创建的,所以我将我的第一个 JPanel 变成了一个类似的 JPanel,并将 getter 和 setter 放入我的框架类。但是代码给了我 NullPointerException 错误。

这是我的课程:

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,但是这个似乎不起作用。

【问题讨论】:

    标签: java swing jframe jpanel getter-setter


    【解决方案1】:

    嗨,Elena,您的面板尚未实例化

    私有静态 JPanel 面板;

    当你打电话时

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-07
      • 2012-03-26
      • 1970-01-01
      相关资源
      最近更新 更多