views:

595

answers:

3

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.

+6  A: 

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.

jjnguy
Thanks. Why was there no mention of this in the tutorial that I read? I learned a lot about fonts and stuff, though...
Thomas Owens
No idea. It is a pretty basic thing to do in Swing.
jjnguy
that's a strange tutorial that seems to contain nothing :Dhere 1.4's javadoc for Graphics2D, it's a much better tutorial than the one you were looking at :Dhttp://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics2D.html
That wasn't supposed to be a tutorial. It is just a link to the Javadocs for Graphics, which has `drawString()` in it.
jjnguy
A: 

Use drawString method of Graphics class. First draw an image and then draw a string. Use ImageIO class to write image object.

adatapost
+2  A: 

if you want to play with the shape of your string (eg: fill:red and stroke:blue):

Graphics2D yourGraphicsContext=(...);
Font f= new Font("Dialog",Font.PLAIN,14);
FontRenderContext frc = yourGraphicsContext.getFontRenderContext();
TextLayout tl = new TextLayout(e.getTextContent(), f, frc);
Shape shape= tl.getOutline(null);

//here, you can move your shape with AffineTransform (...)

yourGraphicsContext.setColor(Color.RED);
yourGraphicsContext.fill(shape);
yourGraphicsContext.setColor(Color.BLUE);
yourGraphicsContext.draw(shape);
Pierre