This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes drawing on the screen in response to user-initiated actions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "drawing on the screen in response to user-initiated actions" Watch "drawing on the screen in response to user-initiated actions" New topic
Author

drawing on the screen in response to user-initiated actions

MR Chen
Ranch Hand

Joined: Aug 10, 2007
Posts: 31
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

Joined: Oct 27, 2005
Posts: 19651
    
  18

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
MR Chen
Ranch Hand

Joined: Aug 10, 2007
Posts: 31

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?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: drawing on the screen in response to user-initiated actions
 
Similar Threads
Using Graphics in a BorderLayout
Transparent Panel on top of Panel?
making image disappeared
setting the background
set the background of a JPanel with an image