Drawing Graphics - Using paint() on Component

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 add the component to the content pane of the frame window.

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

Solution 2: Obviously, solution 1 is not so ideal, because we are drawing on the UI element of the frame itself. To draw graphics only in the content area of the frame, we can create a new component with its own paint() method and add it to the content pane of the frame. The following sample code, JFramePaint2.java, shows you how to do this.

/* JFramePaint2.java
 * Copyright (c) 2014, HerongYang.com, All Rights Reserved.
import java.awt.*;
import javax.swing.*;
public class JFramePaint2 {
   public static void main(String[] a) {
      JFrame f = new JFrame();
      f.setTitle("Drawing Graphics in a Frame"
         +" by Adding a Component");
      f.getContentPane().add(new MyComponent());
   static class MyComponent extends JComponent {
      public void paint(Graphics g) {

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

Note 1: Since no size and location is given to the new added component, it takes the entire area of the content pane, which is the entire area of the frame without the title bar area.

Note 2: Now the origin of the drawing coordinates is at the top left corner of the content pane, much better than solution 1.

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


 PDF Printing Version