Download: java1.zip.

Class Test1 is an example of a simple Java program that provides the starting-point for demonstrating graphics applications. The class provides a JFrame application with a custom client window derived from JPanel.

In this example, the custom JPanel displays the width and height of the client area, centered in the screen. It illustrates the use of FontMetrics to obtain the graphical extent of a text string in Java.

// Test1.java
import java.awt.Graphics;
import java.awt.FontMetrics;
import java.awt.geom.Rectangle2D;
import javax.swing.JPanel;
import javax.swing.JFrame;

public class Test1 extends JPanel
    public void paintComponent(Graphics g)
	super.paintComponent( g );
	int width = getWidth();
	int height = getHeight();
	String str = String.format("width %d height %d",width,height);
	FontMetrics fm = g.getFontMetrics();
	Rectangle2D rect = fm.getStringBounds(str,g);
	width -= rect.getWidth();
	height -= rect.getHeight();

    public static void main( String args[] )
	Test1 panel = new Test1();
	JFrame application = new JFrame("Test1");


Maintained by John Loomis, updated Sun Jan 28 14:20:56 2007