Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Paint rotates arrows

 
M Bryan
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a grid with values and for represanting that values I want to draw an arrow. My code roughly looks like this:



My value lie between 0 and 7, whereas 0 is representing north, 1 north-east, 2 east, ... 7 north-west.
How can I paint my arrow in a way, that it represents the wanted direction?

Thank you
 
Tony Docherty
Bartender
Posts: 2969
59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've moved this to the Swing forum for you.

You can rotate the Graphics object to draw the image in the 8 different directions. Call the rotate() method and specify the number of radians to rotate by.
I've no idea what the performance implications of using rotate are so if this paintComponent method is likely to be called lots of times and you notice redraws are slow it may be more efficient to pre-compute the 8 rotated images either by providing 8 separate images to load or by creating and rotating the 8 images on constructing the object.
 
M Bryan
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a vry good point. I would have to call that method very very often. It's really better to create the images beforehand.
Thank you
 
Campbell Ritchie
Sheriff
Pie
Posts: 49776
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Isn’t rotate a Graphics2D method?
I have had problems with the Affine Transforms of Graphics2D; they are easy to execute and difficult to undo. It is shear that is the worst; you won’t notice much with rotate. But I think you should do several things.
  • 1: Get a copy of the Graphics object.
  • 2: Cast it to Graphics2D.
  • 3: Translate the “origin” to the centre of the panel drawn on.
  • 4: Scale by 1, -1, so y goes upwards.
  • 5: Do your rotation.
  • 6: Discard the graphics object and go back to the original Graphics object.
  • I think rotation is ↺ anti‑clockwise in my example, but you would have to check that. I notice there is a rotate method which does the translation, too. There are 4 affine transforms: shear, rotate, translate and scale.
     
    Tony Docherty
    Bartender
    Posts: 2969
    59
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:Isn’t rotate a Graphics2D method?

    Yes, you are correct it is a Graphics2D method.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic