Test1.javaDownload: 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();
g.drawString(str,width/2,height/2);
}
public static void main( String args[] )
{
Test1 panel = new Test1();
JFrame application = new JFrame("Test1");
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.add(panel);
application.setSize(200,200);
application.setVisible(true);
}
}
Maintained by John Loomis, updated Sun Jan 28 14:20:56 2007