JAVA中提供了一种类Font,专门用来定义字体,关于这个字体的定位需要注意几点:
1.利用Font类的getStringBounds方法来获得包围字符串的矩形;
2.如果要的得到屏幕设备对于字体属性的描述,需要调用Graphics的getFontRenderContext方法;
3.注意几个概念:上坡度,下坡度,行间距,基线,行高,这些大小会用来定义对一个字符串的描述,其中如果得到包围字符串矩阵的边界,对其进行getWidth(),则可得到上坡度+下坡度+行间距;
4.如果想得到下坡度和行间距,需要调用font的getLineMetrics方法,然后利用LineMetrics方法的getDescent获得下坡度,getLeading获得行间距。
5.关于setDefaultCloseOperation方法的说明,只有一个参数,是一个整形参数,0,1,2,3分别代表:
0=DO_NOTHING_ON_CLOSE
1=HIDE_ON_CLOSE(default value)
2=DISPOSE_ON_CLOSE
3=EXIT_ON_CLOSE
下面是今天写的代码:
package font; import java.awt.*; import java.awt.font.*; import java.awt.geom.*; import javax.swing.*; public 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()); pack(); } } 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); double x=(getWidth()-bounds.getWidth())/2; double y=(getHeight()-bounds.getHeight())/2; double ascent=-bounds.getY(); double 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); } }
时间: 2024-11-04 19:14:58