I need to get a mirror of JLabel or JTextArea.
http://www.subirimagenes.net/i/150305101716451074.jpg
If I use a JTextArea, I’ll need the letters are complety mirrored.
If I use a JLabel, I’ll need format and the mirrored letters.
The example was created on Photoshop.
My idea is using graphics(), but I don’t have idea how to do it.
2
Answers
Here’s one way to create a mirror image.
Basically, you print the contents of the JTextArea on a BufferedImage. Then you reverse the pixels of the BufferedImage on the X axis.
Here’s the bad news: It’s not as straight-forward as we might wish, there’s a limitation. In Swing, graphics transformations are applied only on the paint operation, not the general layout and event process. Therefore, in Swing the mirrored component is basically “unusable”, it cannot be used for anything else than displaying the mirror image of the primary component. Coordinates of mouse clicks etc. will be wrong.
Therefore, this is all tricky stuff, a bit hackish.
There are multiple ways how you can do that.
One possibility is to use two views on one model and tell the
Graphics
of one of the views to flip horizontally.Here’s an example how to do so which demonstrates a flipped
JEditorPane
:The advantage of this solution is that the mirror entirely the original component’s MVC and observers because it is the same type of component (View/Controller) on the very same model.
The disadvantage of this solution is that you have create the mirror component in a way that is very specific to the component that is mirrored.
Another possibility is to create a decorator
JComponent
Mirror
which can mirror an arbitrary otherJComponent
. This is a bit tricky, as in Java, decorators cannot override methods of the decorated object, and theMirror
needs to be updated (repainted) as well whenever the original component is updated (repainted).Here’s an incomplete example using a
Mirror
which hooks into the corresponding events. Incomplete because it only hooks intoDocumentEvent
but should also hook onto other events as well, likeCaretEvent
. It would be nice if Swing would have something like aPaintEvent
. As far as I am aware of, it hasn’t. (Well, in fact it has, but there’s no correspondingPaintListener
andaddPaintListener()
.)Also incomplete because the Mirror doesn’t observe the original component’s attributes like size. It only works because the
GridLayout
on theMirrorPanel
keeps the mirror size in sync with the original component.There probably are more possibilities as well. For example, one could override the mirrored component’s
paint()
method to update the mirror component as well. That would get rid of getting notified, but it would lead to unnecessarypaint()
calls in case painting isn’t done due to content change but due to buffer destruction (i.e. other window moved away).