Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Draw on a panel  RSS feed

 
Jose Vives
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. I'm trying draw on a panel inside a frame. But all the time I get 2Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" in the repaintComponent.
This is all the exception error.



and keeps repeating all the time.

the code is the below



I'm trying to implement the langton's ant problem on java. Inside ant.render(g) is jus the follow code


My idea is on repaintcomponent paint the world an the ant positions. But I can't get this work. Any solution? thanks!
 
Campbell Ritchie
Sheriff
Posts: 55333
157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And which line does the Exception occur on?
 
Rob Camick
Ranch Hand
Posts: 2787
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Try changing the order of the above statements. You make the frame visible before you create your Ant class, so the Ant variable will be null when the frame tries to paint itself.
 
Piet Souris
Rancher
Posts: 1943
66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, that's not the problem.

The problem is not uncommon on this site. I've written on this before, but I must say:
this version is very complex and subtle.

First of all: Main extends JPanel, but nevertheless in the 'initG' method another
Main panel is created. However, this panel is not subject to 'initG' and 'init',
so Ant ant gets uninitialized.

The extra complication is that in 'main' all looks okay. a new Main g is created,
and that g is neatly subjected to initG and init. But that is not the panel
that gets added to the frame....

Here is a corrected listing that works. Since I do not have the Cell and Ant classes,
I dropped the Cell and turned Ant into a String. I tried not to change too much,
but OP's construct and mine are still ehh... not 'top notch'.

Greetz,
Piet


 
Stephan van Hulst
Saloon Keeper
Posts: 7713
141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, this is extremely iffy, what with separation of concerns. This is what a Swing frame should look like:

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!