java swing draw centered text

Solutions on MaxInterview for java swing draw centered text by the best coders in the world

showing results for - "java swing draw centered text"
Kourtney
07 Apr 2019
1
2public void centerString(Graphics g, Rectangle r, String s, 
3        Font font) {
4    FontRenderContext frc = 
5            new FontRenderContext(null, true, true);
6
7    Rectangle2D r2D = font.getStringBounds(s, frc);
8    int rWidth = (int) Math.round(r2D.getWidth());
9    int rHeight = (int) Math.round(r2D.getHeight());
10    int rX = (int) Math.round(r2D.getX());
11    int rY = (int) Math.round(r2D.getY());
12
13    int a = (r.width / 2) - (rWidth / 2) - rX;
14    int b = (r.height / 2) - (rHeight / 2) - rY;
15
16    g.setFont(font);
17    g.drawString(s, r.x + a, r.y + b);
18}