Java calling a method from a different class -


i'm doing pretty basic coding, trying call method different class reason i'm getting null pointer exception whenever try call method different class. think i've created instances of class correctly i'm not sure. if can explain what's going wrong me i'd appreciate it.

here class makes call:

 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(); } } 

and here class containing method

public class board extends jpanel{  public board(){ setbackground(color.white); }  public jpanel getpanel(){     return this; }  public void boardtest(){     system.out.print("hello"); } } 

as can see, whenever user clicks button should print out 'hello'.

your code looks though should throw nullpointerexception (npe) when try call board.boardtest() because you're making call before assigning board object board variable , making method call on null variable.

you have create board instance before can try use board variable, board. i.e.,

board board = new board(); 

note 1: similar questions in future, want show exception text , indicate comment in code lines throws exception. i.e.,

@override public void actionperformed(actionevent e) {     board.boardtest();  // **** nullpointerexception thrown here **** } 

note 2: question not swing specific rather basic java issue -- cannot use reference variable until first assign valid object.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -