Java Swing Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 4.00

Drawing Graphics - Using paint() on Content Pane

This section provides a tutorial example on how to override the paint() method in the javax.swing.Component class to draw graphics (a rectangle) and use it as the content pane of the frame window.

Problem: I want to draw some graphics in a frame.

Solution 3: Solution 2 is still not so perfect. Why do we need to add another component for the drawing? Can we draw graphics directly on the content pane? The answer is yes, we can draw directly on the content pane. The following sample code, JFramePaint3.java, shows you how to do this.

/**
 * JFramePaint3.java
 * Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
 */
import java.awt.*;
import javax.swing.*;
public class JFramePaint3 {
   public static void main(String[] a) {
      JFrame f = new JFrame();
      f.setTitle("Drawing Graphics in a Frame"
         +" by Replacing the Content Pane");
      f.setBounds(100,50,500,300);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setContentPane(new MyComponent());
      f.setVisible(true);
   }
   static class MyComponent extends JComponent {
      public void paint(Graphics g) {
         g.drawRect(20,10,100,60);
      }
   }
}

If you run this example, you will get:
Using paint() on Content Pane

Note: The content pane is replaced by a new component object we created with our own the paint() method.

Sample programs listed in this section have been tested with JDK 1.4.2, 1.5.0. and 1.6.0

Last update: 2009.

Sections in This Chapter

Creating Frames with Sizes and Locations

Closing Frame and Terminating Application

Listing and Interrupting AWT Threads

"AWT blocker activation interrupted" Error

Displaying Chinese Characters in Frame Title

Drawing Graphics - Using paint() on Frame

Drawing Graphics - Using paint() on Component

Drawing Graphics - Using paint() on Content Pane

Drawing Chinese Characters on Frames

Dr. Herong Yang, updated in 2009
Drawing Graphics - Using paint() on Content Pane