Monday, February 21, 2011

How to have drawn objects(g.draw(...)) respond to mouse events?

I have this program where it draws a bar graph in a JFrame. The bars of the bar graph change color when I click on them. So my question is whats the best way to approach this? The bruteforce way,i.e. calculate the mouse click and see if it falls within the bars' range, or extends the BufferedImage class and have it implement mouselistener? Because if i were to create a class that extends a jpanel and override its paintcomponent method, it would for sure not run efficiently. And the bars of the bar graph will be animating also, as in values will be fed to the program and the graphs get updated all the time.

From stackoverflow
  • I would personally go for the "listen for clicks over the whole component and work out which bar a click falls on". It shouldn't be hard to do - just division to work out which bar, then a bounds check to work out if the particular bar is long enough for that point to be painted.

    Introducing "one control per bar" feels like a recipe for trouble in terms of getting layout etc right. I'm sure it can be done - and I'm sure those with more GUI experience have less trouble with layout than I do - but I strongly suspect it would much more work.

    vamsi : Ya i figured, just wanted to see if there were any other ways, better ways that is. Thanks.

0 comments:

Post a Comment