Using Java's Graphics or Graphics2D classes, how do I paint a String?

graphics, graphics2d, java, paint, swing

Solution

Check out the following method.

g.drawString();

The `drawString()` method will do what you need.

An example use:

protected void paintComponent(Graphics g){
    g.setColor(Color.BLACK);
    g.drawString(5, 40, "Hello World!");
}

Just remember, the coordinates are regarding the bottom left of the `String` you are drawing.

Problem

I have a `String` and I want to paint it onto an image. I am able to paint points and draw lines, however, even after reading the Text part of the 2D Graphics tutorial, I can't figure out how I can take a `String` and paint it onto my drawing. Unless I'm looking at the wrong tutorial (but it's the one I get whenever I search for anything about Java and painting Strings using `Graphics` or `Graphics2D`), I'm still stumped.

Original source