Draw font inside a Rectangle : Font « 2D Graphics GUI « Java






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

}
           
         
    
    
    
  








Related examples in the same category

1.Ascii font pattern
2.A cache of the dynamically loaded fonts found in the fonts directory
3.Load font from ttf file
4.Outline Font paintOutline Font paint
5.Font paintFont paint
6.Font DerivationFont Derivation
7.Font centeredFont centered
8.Font ListFont List
9.FontDemo lists the system fonts and provides a sample of each one(Have some problems)
10.Finds and displays available fonts
11.Obtain FontMetrics of different fonts
12.Display font in a grid
13.Create font from true type font
14.Wrap string according to FontMetrics
15.Draw base line and enclosing line for a font
16.List all Fonts