I need to use the Graphics object outside of the paint(Graphics g) method in a class that extends Canvas. I don't need to redraw anything; I just need to measure fontheights and string widths and so forth, i.e. use methods only available in the Graphics class.
I've tried things like ...
textHeight = Graphics.getFont().getHeight();
...etc, but I'm told that I can't use these non-static functions. I know I can't just instantiate a Graphics class like so ...
Graphics myG = new Graphics();
.... as it won't have the proper graphics context to use. Is there any way from within a canvas class to get a hold of the Graphics context from outside the paint() method? Something like ....
If you have a Canvas class then I guess you want to draw something even if not redraw it. For that first draw the graphics context is required. You have to use it from the paint method as it is supplied by the framework.
Sorry; I DO need to draw something on the canvas of course, but after that I need to use it to perform some none drawing-related operations, specifically to measure fontHeights and variable-length string widths to perform some text wrapping later on. I need to be able to use the Graphics object outside of the paint() method. I can't just pass it from the paint method to the function I need as it's a user-triggered event, and no painting is performed.
If the only thing you need to access in those other methods is the width and height of your font then I suggest you solve the problem by simply keeping track of the Font you're using with a Font variable. (Or more if you use multiple fonts)
private Font f = Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_PLAIN,Font.SIZE_SMALL);
After that you can then in your code check the height of that by just calling
and if you want the width of a string then simply call