Test1.java
Download source code
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.
This version initializes the user interface in the event dispatch thread. It used to be perfectly acceptable to carry out the intialization in the main thread. Sadly, as Swing components have gotten more complex, it is not possible to guarantee the safety of that approach. The probability of an error is extremely low, but at least you know how to do the right thing.
01: // Test1.java 02: import java.awt.EventQueue; 03: import java.awt.Graphics; 04: import java.awt.FontMetrics; 05: import java.awt.geom.Rectangle2D; 06: import javax.swing.JPanel; 07: import javax.swing.JFrame; 08: 09: public class Test1 extends JPanel 10: { 11: public void paintComponent(Graphics g) 12: { 13: super.paintComponent( g ); 14: int width = getWidth(); 15: int height = getHeight(); 16: String str = String.format("width %d height %d",width,height); 17: FontMetrics fm = g.getFontMetrics(); 18: Rectangle2D rect = fm.getStringBounds(str,g); 19: width -= rect.getWidth(); 20: height -= rect.getHeight(); 21: g.drawString(str,width/2,height/2); 22: } 23: 24: public static void main( String args[] ) 25: { 26: EventQueue.invokeLater(new Runnable() 27: { 28: public void run() 29: { 30: Test1 panel = new Test1(); 31: JFrame application = new JFrame("Test1"); 32: application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 33: application.add(panel); 34: application.setSize(200,200); 35: application.setVisible(true); 36: } 37: }); 38: } 39: }
Maintained by John Loomis, updated Wed Mar 12 10:37:27 2008