Big Data and Hadoop Training @$80 or Rs. 6,000 only - valid till Oct 17th Apply Now!

Show String in Oval

Ads
 

Show 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 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

Ads

Ads