编写一个小程序,以黄色圆圈显示蓝色的“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);
}
答案 0 :(得分:1)
水平绘制字符串:java.awt.Graphics2D.drawString()
选择一种字体,然后使用java.awt.Graphics.setFont()
要知道文字延伸:java.awt.FontMetrics.stringWidth()
要了解如何在Java中使用2D图形: The Java Tutorial: Trail: 2D Graphics
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 );
}
}