• Post Reply Bookmark Topic Watch Topic
  • New Topic

problem with paint()

 
Raghav Puranmalka
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
im trying to make a blackjack game with graphics. I have a text based version running and I have a problem with the GUI. I am using KeyEvents to listen to what the user wants to do (i.e. hit, stay, etc). My paint method calls a play() method which asks for bet, displays cards etc. Then it is supposed to wait for a keyEvent and then act accordingly. The problem is that the play() method ends before the keyEvent occurs and paint gets control back and loops incessently. I tried to have a loop right before play() ends to wait until the method is complete but it doesn't work. I am kind of crunched for time so please help me out. Thanks.
 
Craig Wood
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Without some code we are limited in how much we can help. So I'll try to give some general advice that you will have to translate into your coding.

In general it is poor practice to put event handling code in your paintComponent method. Think of paint or paintComponent as having the sole purpose of rendering the graphical state of your app, specifically , painting exactly what you give/tell it to paint. Swing calls these methods for it's own reasons and needs whenever it likes. You may call it (via repaint) when you need to update the state in graphics representation.

All monitoring for user input, collection of data and computation must (my recommendation anyway) take place completely independent of the painting code. In more complex programs the event–handling work is often better placed in separate classes form the class that does the rendering. This makes for ease in conceptualizing, designing, class communication, reading, and code maintenance.
So:

Methods return as soon as the code in them executes. Listeners will report events as they are received. It all starts with the listeners. You can put all you code in the listener (for simple apps) or call methods that will do the work. At the end of gathering, computing, settingVariables you call repaint to show the changes.
[ May 30, 2004: Message edited by: Craig Wood ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!