Java Graphics How to - Draw a string inside a Rectangle








Question

We would like to know how to draw a string inside a Rectangle.

Answer

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
//w  ww .j a  va2  s  .co  m
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new TestPane());
    frame.pack();
    frame.setVisible(true);
  }
}

class TestPane extends JPanel {
  public TestPane() {
    setBackground(Color.BLACK);
  }

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

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setColor(Color.RED);
    g2d.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2);
    g2d.drawLine(getWidth() / 2, 0, getWidth() / 2, getHeight());
    render(g);
    g2d.dispose();
  }

  public void render(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(Color.WHITE);
    Font font = new Font("Verdana", Font.PLAIN, 20);
    g2d.setFont(font);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    FontMetrics fm = g2d.getFontMetrics();

    String option = "This is a test";

    int x = (getWidth() - fm.stringWidth(option)) / 2;
    int y = ((getHeight() - fm.getHeight()) / 2);
    g2d.drawString(option, x, y + fm.getAscent());
    g2d.drawRect((int) x - 20, (int) y - 10, (int) fm.stringWidth(option) + 40,
        (int) fm.getHeight() + 20);
  }
}