Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

drawing on the screen in response to user-initiated actions

 
MR Chen
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So I'm making a game, in which the player plays a card (by clicking the button associated with that card) to add a piece to the board in a new square.

I have this piece of code to draw the board:



which works fine, but I can't figure out how to actually get the NEW pieces drawn on the board.

In Head First Java, there's an example where you push a button to randomly change the color of a circle, but all it does is call a repaint on the whole frame - because the color picking code is actually inside the paintComponent method, it works fine for that purpose. What I'm trying to do is add something that wasn't there previously.

I tried to add a second method to the class (additions in bold):

but it doesn't work because g is out of scope for the addCrown method.

Can anyone point me in the right direction on this?

Thanks,
Mike
 
Rob Spoor
Sheriff
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Store a reference to all your pieces, then draw them all in your paintComponent. A list or array could be used for the storing.

Two more tips:
1) keep paintComponent protected. There is no need for it to be public
2) don't forget to call super.paintComponent(g), otherwise the panel will not paint itself properly
 
MR Chen
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Store a reference to all your pieces, then draw them all in your paintComponent.

Thanks for the tip! I already had a multidimensional array to keep track of which pieces were in each square, but was keeping it somewhere else. It really does make more sense to put it here.

I actually feel lost as far as displaying graphics goes. Anybody know any good tutorials/books?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic