-2

Write an applet that displays “UT” in blue in a yellow circle Here is the code

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);

}
Akmal Rasool
  • 496
  • 2
  • 7
  • 17

1 Answers1

1

To draw a string horizontally: java.awt.Graphics2D.drawString()

Choose a font, and apply it to the graphics context with java.awt.Graphics.setFont()

To know the text extends: java.awt.FontMetrics.stringWidth()

To learn how to use 2D graphics in Java: 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 );
   }
}
Aubin
  • 14,617
  • 9
  • 61
  • 84