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) 2014, HerongYang.com, All Rights Reserved.
 */
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 to 1.8.0.

Last update: 2014.

Table of Contents

 About This Book

 Introduction of Java Swing Package

 Graphics Environment of the Local System

JFrame - Main Frame Class

 Creating Frames with Sizes and Locations

 Closing Frame and Terminating Application

 Listing and Interrupting AWT Threads

 "AWT blocker activation interrupted" Error

 "AWT blocker activation interrupted" Error in JDK 1.7

 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

 JLabel - Swing Label Class

 JButton - Swing Button Class

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

 Menu Bar, Menus, Menu Items and Listeners

 Creating Internal Frames inside the Main Frame

 Layout of Components in a Container

 LookAndFeel and UIManager

 Option Dialog Boxes

 JEditorPane - The Editor Pane Class

 SwingWorker - The Background Task Worker

 References

 PDF Printing Version