This problem was recently encountered when developing a similar report component.
At the beginning of the development of this component was the use of Jfreechart, the open Source tool, after two days of trying to give up. The main reason is that if I want to expand the functionality of the component, Jfreechart not very good operation, and finally realized this thing, in fact, it is not very troublesome. The main use of graphics2d for graphic drawing.
In the development of the component, you need to draw the title of each data under the report, but do not know the font information, and do not know how long the title, this time to get the title of the number of pixels,
If you need to wrap the line, and to dynamically control the height of each row, not because the font information changes at random.
The following code is given:
/** * Get the longest text in all point information * * @param g2d * @param font * @return * @parm * @exception */public double getmaxfontwidth (Graphics2 D g2d, font font) {Double maxWidth = 0;for (String key:pointsInfo.keySet ()) {Double fontSize = getfontsize (g2d, Font, key if (MaxWidth < fontSize) {maxWidth = FontSize;}} return maxWidth;} /** * Gets the height of the text corresponding to the font * * @param g2d * @param font * @return * @parm * @exception */public double getfontheight (graphics2d g 2d, font font) {//Set large font FontRenderContext context = G2d.getfontrendercontext ();//Get font Pixel Range object Rectangle2D stringbounds = f Ont.getstringbounds ("W", context);d ouble fontwidth = Stringbounds.getwidth (); return fontwidth;} /** * Gets the length of the corresponding text * * @param g2d * @param font * @return * @parm * @exception */public double getfontsize (graphics2d G2 d, font font, String text) {//Set large font FontRenderContext context = G2d.getfontrendercontext ();//Gets the font's pixel Range object Rectangle2D stri Ngbounds = font.getstringbounds (text, context);d ouble fontwidth = Stringbounds.getwidth (); return fontwidth;}
Because of the need to go back to all the title of the longest information, by the way the code is also posted out.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java AWT gets the occupied pixels based on the information and font of the string