Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Example Java Swing Graphics2D Show String in Oval

Related Tutorials


 
 

Share on Google+Share on Google+

Show String in Oval

Advertisement
To show a string in oval, we are providing you an example. A font 'Book Antiqua' is defined to display the string 'WELCOME'.

Show String in Oval

     

This section illustrates you how to show the string in Oval.

To show a string in oval, we are providing you an example. A font 'Book Antiqua' is defined to display the string 'WELCOME'. To render the particular font on the screen, we have used the class FontMetrics. The object of FontMetrics class encapsulates all the information. 

The method drawOval() draw an oval shape. The char ch = st.charAt(k) retrieves the k character on each iteration. The method getHeight() of class FontMetrics  gets the standard height of a line of text in the given font. The method charWidth(ch) of class FontMetrics returns the width of the specified character in the given font. 

Following code draws the string in oval:

g.drawString(String.valueOf(ch), x, y + h);

Here is the code of ShowFontInOval.java

import java.awt.*;
import javax.swing.*;

public class ShowFontInOval extends JPanel {
  public void paint(Graphics g) {
  g.setFont(new Font("Book Antiqua",0,90));
  g.setColor(Color.cyan);
  FontMetrics fontMetrics = getFontMetrics(new Font
   (
"Book Antiqua",0,90));
  String st = "WELCOME";
  int x = 1;
  int y = 1;
  for (int k = 0; k < st.length(); k++) {
  char ch = st.charAt(k);
  int h = fontMetrics.getHeight();
  int w = fontMetrics.charWidth(ch);
  g.drawOval(x, y, w, h);
  g.drawString(String.valueOf(ch), x, y + h);
  x= x + w;
  }
  }
 public static void main(String[] args) {
 JFrame f = new JFrame("Show string in Oval");
 f.setContentPane(new ShowFontInOval());
 f.setSize(520300);
 f.setVisible(true);
  }
}

Output will be displayed as:

Download Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 11, 2008

Related Tutorials

Discuss: Show String in Oval  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com