StringRectPaintPanel.java Source code

Java tutorial

Introduction

Here is the source code for StringRectPaintPanel.java

Source

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

}