Search code examples
javaswingrotationjpanel

Can you create a JPanel that is rotated?


I was wondering if there might be a way using Java Swing to create a rotated JPanel? I'd read other questions/answers on this topic but I didn't understand if you could create one already rotated or not. It does not need to rotate once it's created, only be created tilted on the x/y axis. Thanks.

Thanks, quite helpful!


Solution

  • You can't get this behavior by default. However, you could extend JPanel and get the desired rotation behavior if you do a little linear algebra:

    1. Override the paint(Graphics g) method. You could have it first paint to an instance of BufferedImage, then use a rotation matrix to rotate that image before drawing it on the underlying panel.

    2. Override all methods that handle mouse input and apply the reverse rotation to the coordinates passed in by the associated listeners. This way, the underlying layout manager still 'thinks' that the panel hasn't been rotated, but you've rotated the drawing and event notification so that things still "line up" properly.

    I'll caveat all of this by saying I've never done this before, and you could run into unexpected issues not outlined here, but I do have about 10 years of experience with Java Swing and this is how I'd do it if I had to.