3

I have a font object and a String. I want to return a Shape Object that is a representation of the String. I have a whole bunch of other classes that will display the String and take care of it.

I'm having trouble figuring out how to do this when I do not have a graphics/graphics2d object. Any Help? I have searched the net but had trouble finding helpful links.

public class SpecializationOfTester extends ParentTester {

    private String      str;
    private Font        font;


    public SpecializationOfTester(String str, Font font) {
        this.font = font;
        this.str = str;
    }

    public Shape getShape()
    {
        Shape           s;
        //
        //
        return s;
    }

}

Thanks

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • You could always create a `Graphics2d` object. – John Dvorak Oct 25 '12 at 16:27
  • Can I can use that Shape I end up with and add it to a different Graphics object later? –  Oct 25 '12 at 16:28
  • I guess it is so. At worst, a `Graphics2D` object will be held by the `Shape` and consume some memory. – John Dvorak Oct 25 '12 at 16:33
  • Am I able to do that if this class extends a parent class? I changed my example –  Oct 25 '12 at 16:34
  • Every class extends some other class. If you don't extend explicitly, 'Object' is used. – John Dvorak Oct 25 '12 at 16:35
  • Okay. I think I'm confused though. How do you create a Graphics2D object since its constructor protected? –  Oct 25 '12 at 16:39
  • See trashgod's answer. You can get one by creating a `BufferedImage` and getting the graphics object from that. Check out the answer he linked in the comments. – Brian Oct 25 '12 at 16:41

1 Answers1

6

You can use GlyphVector#getOutline(), as mentioned here. You can create a graphics context in a BufferedImage, as discussed in Using Headless Mode in the Java SE Platform.

See also these appealing examples:

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 2
    [Also a relevant example](http://stackoverflow.com/a/2466283/646634) that gets the `Shape` from a graphics object. – Brian Oct 25 '12 at 16:42
  • Hey I read it and it worked! I was able to do what I needed with the Shape I created and everything worked (strangely) perfectly! Thanks for all the help people. –  Oct 25 '12 at 16:58