Java provides a class font that is specifically used to define fonts, and there are a few things to note about the positioning of the font:
1. Use the Getstringbounds method of the font class to obtain a rectangle enclosing the string;
2. If you want to get the screen device for the description of font properties, you need to call the graphics Getfontrendercontext method;
3. Note Several concepts: Upper slope, downhill degree, line spacing, baseline, row height, these sizes will be used to define a string description, where if you get the boundary of the string matrix, getwidth (), you can get the upper slope + lower slope + line spacing;
4. If you want downhill and line spacing, you need to call the Getlinemetrics method of the font and then use the getdescent of the LineMetrics method to get the downhill degree, getleading get the line spacing.
5. For a description of the Setdefaultcloseoperation method, there is only one parameter, which is an shaping parameter, 0,1,2,3 represents:
0=do_nothing_on_close
1=hide_on_close (default value)
2=dispose_on_close
3=exit_on_close
Here is the code written today:
Package Font;import java.awt.*;import java.awt.font.*;import java.awt.geom.*;import javax.swing.*;p ublic class Fonttest{public static void Main (string[] args) {Eventqueue.invokelater (new Runnable () {public void run () {JFrame frame= New Fontframe (); Frame.settitle ("fonttest"); Frame.setdefaultcloseoperation (Jframe.exit_on_close); Frame.setvisible (True);}});}} Class Fontframe extends Jframe{public Fontframe () {Add (New Fontcomponent ());p ack ();}} Class Fontcomponent extends jcomponent{private static final int default_width=300;private static final int default_height =200;public void Paintcomponent (Graphics g) {graphics2d g2= (graphics2d) G; String message= "Hello world!"; Font f=new font ("Serif", font.bold,36); G2.setfont (f); FontRenderContext Context=g2.getfontrendercontext (); Rectangle2D bounds=f.getstringbounds (message,context);d ouble x= (getwidth ()-bounds.getwidth ())/2;double y= ( GetHeight ()-bounds.getheight ())/2;double ascent=-bounds.gety ();d ouble basey=y+ascent;g2.drawstring (message, (int) x, (int) basey); G2.sEtpaint (Color.light_gray); G2.draw (New Line2d.double (X,basey,x+bounds.getwidth (), Basey)); Rectangle2D rect=new rectangle2d.double (X,y,bounds.getwidth (), Bounds.getheight ()); G2.draw (rect);} Public Dimension getPreferredSize () {return new Dimension (default_width,default_height);}
JAVA Swing Learning Form text display