Draw box centered string in Java

Description

The following code shows how to draw box centered string.

Example


import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.SystemColor;
//from  w ww . java 2 s . c  om
import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    g.translate (200, 100);
    String text = "java2s.com";
    FontMetrics fm = g.getFontMetrics();
    Dimension size=new Dimension(100,100);
    int x = (size.width - fm.stringWidth(text))/2;
    int y = (size.height - fm.getHeight())/2;
    g.setColor (SystemColor.control);
    g.fillRect (0, 0, size.width, size.height);
    g.setColor (SystemColor.controlShadow);
    g.drawLine (0, 0, 0, size.height-1);
    g.drawLine (0, 0, size.width-1, 0);
    g.setColor (SystemColor.controlDkShadow);
    g.drawLine (0, size.height-1, size.width-1, size.height-1);
    g.drawLine (size.width-1, 0, size.width-1, size.height-1);
    g.setColor (SystemColor.controlText);
    g.drawString (text, x, y);
  }
}

public class Main {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 450, 450);
    window.getContentPane().add(new MyCanvas());
    window.setVisible(true);
  }
}

The code above generates the following result.

Draw box centered string in Java




















Home »
  Java Tutorial »
    Graphics »




Animation
BufferedImage
Color
Font
Gradient
Graphics Settings
Image
Mouse Draw
Print
Shape
Text
Transform