TitledBorder in JPanel moves when translate() method is used

Viewed 527

I have created a JPanel and add it on a JFrame. JPanel has TitledBorder, but when I use the method translate(), e.g.,

g2.translate(getWidth() / 2, getHeight() / 2);

the whole component, including the border is translated. The effect is presented on Figure 1. Figure 1

The desired result is depicted on the figure below. Figure 2

Code is pasted below.

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;

class GPanel extends JPanel {
    private void doDrawing(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.translate(getWidth() / 2, getHeight() / 2);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        doDrawing(g);
    }
}

class Main extends JFrame {
    public Main() {
    }

    public static void main(String[] args) {
        Main ex = new Main();
        ex.setSize(new Dimension(400, 400));
        GPanel panel = new GPanel();
        panel.setBorder(BorderFactory.createTitledBorder("Title"));
        ex.add(panel);
        ex.setLocationRelativeTo(null);
        ex.setVisible(true);
    }
}
3 Answers
Related