Question

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.

Was it helpful?

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.

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top