为何执行结果是这个样子_JDK1.7
为什么执行结果是这个样子_JDK1.7
理论上应该出现“Hello World!”的字样,怎么执行结果是这个样子,不解
理论上应该出现“Hello World!”的字样,怎么执行结果是这个样子,不解
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); } }