浏览 3043 次
锁定老帖子 主题:为什么执行结果是这个样子_JDK1.7
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2014-09-04
package com.practice.test; import java.awt.*; import java.awt.font.*; import java.awt.geom.*; import java.awt.geom.Ellipse2D.Double; import javax.swing.*; /** * 测试字体相关 * @author KangMing * @version 1.7 2014-09-03 */ public class FontTest { public static void main(String[] args){ EventQueue.invokeLater(new Runnable(){ public void run(){ FontFrame frame = new FontFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } /** * A frame with a text message component * */ class FontFrame extends JFrame{ public FontFrame(){ setTitle("FontTest"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); //将组件加到框架中 FontComponent component = new FontComponent(); add(component); } public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; } class FontComponent extends JComponent{ public void FontComponent(Graphics g){ Graphics2D g2 = (Graphics2D) g; String message = "Hello World!"; Font f = new Font("Serif", Font.BOLD, 36); g2.setFont(f); //measure the size of the message FontRenderContext context = g2.getFontRenderContext(); Rectangle2D bounds = f.getStringBounds(message, context); //set(x, y) = top - left corner of text double x = (getWidth() - bounds.getWidth()) / 2; double y = (getHeight() - bounds.getHeight()) / 2; //add ascent to y to reach the baseline double ascent = -bounds.getY(); double baseY = y + ascent; //draw the message g2.drawString(message, (int) x, (int) baseY); g2.setPaint(Color.LIGHT_GRAY); //draw the baseline g2.draw(new Line2D.Double(x, baseY, x + bounds.getWidth(),baseY)); //draw the enclosing rectangle Rectangle2D rect = new Rectangle2D.Double(x, y, bounds.getWidth(),bounds.getHeight()); g2.draw(rect); } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2014-09-04
这行声明不是constructor:
public void FontComponent(Graphics g) |
|
返回顶楼 | |
发表时间:2014-09-05
RednaxelaFX 写道 这行声明不是constructor:
public void FontComponent(Graphics g) 多谢指点,这个地方应该是 public void paintComponent(Graphics g) |
|
返回顶楼 | |