Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java center text in rectangle

I use drawString() method to draw string using Graphics, but I want to center my text in a rectangle. How should I do that?

like image 572
Luka Tiger Avatar asked Jan 11 '13 18:01

Luka Tiger


1 Answers

Centering text has a lot of "options". Do you center absolutely or based on the base line??

enter image description here

Personally, I prefer the absolute center position, but it depends on what you are doing...

public class CenterText {

    public static void main(String[] args) {
        new CenterText();
    }

    public CenterText() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            int height = getHeight();
            String text = "This is a test xyx";

            g.setColor(Color.RED);
            g.drawLine(0, height / 2, getWidth(), height / 2);

            FontMetrics fm = g.getFontMetrics();
            int totalWidth = (fm.stringWidth(text) * 2) + 4;

            // Baseline
            int x = (getWidth() - totalWidth) / 2;
            int y = (getHeight() - fm.getHeight()) / 2;
            g.setColor(Color.BLACK);

            g.drawString(text, x, y + ((fm.getDescent() + fm.getAscent()) / 2));

            // Absolute...
            x += fm.stringWidth(text) + 2;
            y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
            g.drawString(text, x, y);

        }

    }

}
like image 192
MadProgrammer Avatar answered Sep 28 '22 10:09

MadProgrammer