Source Code : Draw font inside a Rectangle

Java Is Open Source Programming Language You Can Download From Java and Java Libraries From http://www.oracle.com. Click Here to download
We provide this code related to title for you to solve your developing problem easily. Libraries which is import in this program you can download from http://www.oracle.com. Click Here or search from google with Libraries Name you get jar file related it

Draw font inside a Rectangle

     

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class StringRectPaintPanel extends JPanel {
  public void paint(Graphics g) {
    g.setFont(new Font("",0,100));
    FontMetrics fm = getFontMetrics(new Font("",0,100));
    String s = "java2s";
    int x = 5;
    int y = 5;
    
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);

      int h = fm.getHeight();
      int w = fm.charWidth(c);

      g.drawRect(x, y, w, h);
      g.drawString(String.valueOf(c), x, y + h);

      x = x + w;
    }
  }

  public static void main(String[] args) {

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setContentPane(new StringRectPaintPanel());
    frame.setSize(500, 300);
    frame.setVisible(true);
  }

}
           
         
    
    
    
  

Thank with us