Search code examples
javaswingjlabelrotatetransform

Vertical JLabel Alignment


I was looking for a way to rotate JLabel vertically and I found that several posts related to this topic suggest to use Graphics2d. But, in this way, the size of my JLabel is inconsistent (widht & height inverted).

enter image description here

I found also that another user, here, suggested this code. Actually, the code works, but there are no indications about how to align the text of the JLabel, and this is what i get:

enter image description here

Can anyone help with any of the two methods (controlling size in method one or 1 aligning text in method 2)?

Thank you very much in advance.


Solution

  • One way is to create an Icon of the text and rotate the Icon then add the Icon to the label. Then the size of the label will be calculated normally.

    Check out the Rotated Icon class for an example of this approach. You will also need the TextIcon class.

    These two classes may seem like extra work, but it is an example of how to create reusable classes to you don't do custom painting all the time.