swing - Java 2D NullPointerException -


recently i've started coding java 2d.

i made this:

    public void paintcomponent(graphics comp) {          graphics2d comp2d = (graphics2d) comp;          font fontx = new font("verdana", font.bold, 5);          comp2d.setfont(fontx);          comp2d.drawstring("hello world!", 5, 50); }   

i did import jframe , java.awt.*, there's still problem.

when run it, this:

    exception in thread "main" java.lang.nullpointerexception     @ game.game.paintcomponent(game.java:41) - comp2d.setfont(fontx); - sets font     @ game.game.next(game.java:36) - paintcomponent(null); - calls paintcomponent public void next() public void     @ game.game.main(game.java:26) - next.next(); - calls public void called "next" using object called "next" (this public void throws interruptedexception) java result: 1 

how can solve it?

you state:

exception in thread "main" java.lang.nullpointerexception @ game.game.paintcomponent(game.java:41) -       comp2d.setfont(fontx); - sets font 

this means comp2d null , you're trying call method on null variable.

at game.game.next(game.java:36) - paintcomponent(null);       - calls paintcomponent public void next() public void 

this means you're calling paintcomponent directly , passing in null!

so you're calling paintcomponent directly , passing in null! should come no surprise graphics object null , throw npe if try call methods on it.

solution:

  • you never call paintcomponent directly.
  • instead have jvm call when call repaint(). jvm pass in valid graphics object.
  • most important -- read painting swing tutorial. can't guess @ stuff , expect work.
  • be sure paintcomponent method held within jpanel or other jcomponent derived component.
  • be sure override valid using @override annotation paintcomponent.
  • don't neglect call super.paintcomponent(...) method within override.
  • for example, have other method change class field, have change string field called text, call repaint(), , have paintcomponent(...) method use text field text print in jpanel. example. can change of drawing component's fields, , use them inside of paintcomponent(...).

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

php - Accessing static methods using newly created $obj or using class Name -