• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

how to get paintComponent to respond to a variety of events

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I am starting on a program that will show different graphical effects, depending on which button is pushed. So I know I need to use paintComponent, but it seems so un-OO to have a single method with a long list of if-then-else-if... to cover all the possible graphical effects. So before I get too far into it, I wanted to ask advice -- is this the best (or only) way to do what I'm trying to do?

In the code below there are 2 buttons, one draws a square, one draws a circle. I extend JPanel as an inner class, and use an instance variable (ev) to keep track of which button was pushed so paintComponent knows which shape to draw.

Everything about this program feels clunky and wrong to me...

Thanks for any advice!!
-Karen.


 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Imagine an interface "Effect":



and a collection of these:

HashMap<String, Effect> effects = new HashMap<String, Effect>();
map.put("circle", new CircleEffect());
map.put("square", new SquareEffect());
...

and then a paintComponent() method that does:



Now you can add as many effects as you want, and the paintComponent() method doesn't change. No if/else, no switch, just object oriented goodness.
 
Karen Nelson
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you, it works!! I'm so glad I didn't get tangled up in the old code!
reply
    Bookmark Topic Watch Topic
  • New Topic