我正在做一些非常基本的编码,试图从一个不同的类调用一个方法,但由于某种原因,每当我尝试从任何不同的类调用任何方法时,我都会得到一个空指针异常.我想我已经正确地创建了类的实例,但我不确定.如果有人能解释我的错误,我会很感激.
这是进行调用的类:
public class Menu extends JPanel implements ActionListener{
Skeleton skeleton;
Board board;
public Menu(){
setBackground(Color.BLACK);
JButton button = new JButton("hello");
button.addActionListener(this);
this.add(button);
}
public JPanel getPanel(){
return this;
}
@Override
public void actionPerformed(ActionEvent e) {
board.boardTest();
}
}
Run Code Online (Sandbox Code Playgroud)
这是包含该方法的类
public class Board extends JPanel{
public Board(){
setBackground(Color.WHITE);
}
public JPanel getPanel(){
return this;
}
public void boardTest(){
System.out.print("hello");
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,每当用户单击按钮时,它应打印出"hello".