package swing;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
/**
* 字符占据的宽和高的像素数量
*/
public class FontTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
FontFrame frame = new FontFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class FontFrame extends JFrame {
public FontFrame() {
this.setTitle("FontTest");
this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
FontComponent component = new FontComponent();
this.add(component);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}
class FontComponent extends JComponent {
@Override
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 = (this.getWidth() - bounds.getWidth()) / 2;
double y = (this.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);
}
}