Search code examples
javaswingscalingjtextareapaintcomponent

How can I scale JComponents up or down?


In my application, I need to draw JTextArea on certain position on my panel, and I need to be able to zoom in and out on it.

For positioning it, I can use absolute positioning, but scaling poses a challenge - I can easily scale it down by tweaking paintComponent method:

@Override
public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.scale(0.5,0.5);
    super.paintComponent(g2);
}

But scaling up doesn't work - since I set the bounds of the component using setBounds explicitly, part of scaled up component ends up not being drawn. How can I solve it?

EDIT: A bit of explanation.

The application I maintain is a sort of a graphic editor, and I need to add a functionality of adding a something like a note to working area, so that user can directly type the text on that working area. As in most graphic editors, the working area can be moved and zoomed in/out, so the text area where user is typing the text should move and scale too.


Solution

  • If the text component must remain editable when scaled, you may be able to scale the Font used in (rough) proportion to the scale factor, as shown here.

    image