编写一个小程序,在黄色圆圈中以蓝色显示“UT” 这是代码
public void paint(Graphics g) {
g.setColor(Color.blue);
Font f = new Font("TimesRoman", Font.PLAIN, 72);
g.setFont(f);
g.drawString("UT.", 10, 30);
g.fillOval(100,100,100,100);
}
要水平绘制字符串:java.awt.Graphics2D.drawString()
选择一种字体,并将其应用于图形上下文java.awt.Graphics.setFont()
要知道文本扩展:java.awt.FontMetrics.stringWidth()
学习如何在 Java 中使用 2D 图形:Java 教程:Trail:2D 图形
import java.awt.Canvas;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Application extends Frame {
class DrawingText extends Canvas {
private static final String LABEL = "In a circle";
private static final int MARGIN = 8;
@Override
public void paint( Graphics g ) {
super.paint( g );
Font pretty = new Font( "Lucida Sans Demibold", Font.BOLD, 12 );
g.setFont( pretty );
FontMetrics fm = g.getFontMetrics();
int width = fm.stringWidth( LABEL );
int tx = getWidth ()/2 - width/2;
int ty = getHeight()/2 + fm.getAscent()/4;
int cx = tx - MARGIN;
int cy = getHeight()/2 - width/2 - MARGIN;
g.drawString( LABEL, tx, ty );
g.drawArc( cx, cy, width+2*MARGIN, width+2*MARGIN, 0, 360 );
}
}
Application() {
super( "UT in a circle" );
add( new DrawingText());
setSize( 300, 300 );
setLocationRelativeTo( null );
addWindowListener( new WindowAdapter() {
@Override public void windowClosing(WindowEvent e) {
System.exit( 0 ); }});
}
public static void main( String[] args ) {
new Application().setVisible( true );
}
}