• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to get paintComponent to respond to a variety of events  RSS feed

 
Karen Nelson
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • 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.


 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thank you, it works!! I'm so glad I didn't get tangled up in the old code!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!