0

So the program draws a car and I'm going to make three buttons, one for flash to initialize the flashing ability, one left, to move the car one space to the left and one right, to move the car one space to the right. My question is how do I make it change color each time I press the button? So to sum it up, I don't know how to have an object change it's color each time the button is pressed while flashing is on. I assume I use paint()

Any help would be appreciated.

2 Answers2

0

If you are drawing an image, you will need to load a different image file which is a different color, and then draw that image instead. You will do this inside whatever method you are currently using to draw the car.

If you are drawing a shape or text of some kind, you can call g.setColor() on the graphics object passed to the paint() or paintComponent() method before drawing the shape.

nhouser9
  • 6,730
  • 3
  • 21
  • 42
0

There are any number of ways to do it. The basic requirement though, is to have a Object of some kind which you can tell when it should change color, it would then undertake the appropriate action and update the UI accordingly.

You could...

Use a simple JPanel as the representation of the object and simply call it's setBackground color method when you want it to change color.

This assumes you want to make use of a LayoutManager to position the panel. While it is certainly doable, it will require some thought into the overall design

You could...

Use a JPanel and override it's paintComponent method and paint the color change there. At the simplest level, this is overkill, but if you also want to draw a "car" or an image of "car", then this becomes a little more meaningful, especially if you want to rotate the car based on the direction it's moving

See Painting in AWT and Swing, Performing Custom Painting and 2D Graphics for more details

Flashing

I assume you mean you want the object to be animated in some way and "blink" on and off.

This can easily be accomplished through the use of a Swing Timer which can be used to change the state of a simple flag which changes the way in which the component is rendered.

See How to use Swing Timers for more details

The important concept to take away from this is to create a object which encapsulates the requirements in away which is ease for you to use, so when you enable flashing for example, all you do is call the setFlashing(boolean) method and the object takes care of the rest

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Would anyone care to highlight the reason for the downvote? In what way(s) does it not answer the OPs questions? In what ways can it be improved? – MadProgrammer May 15 '16 at 02:52