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) 1997-2024 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.setBounds(100,50,500,300);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.getContentPane().add(new MyComponent());
      f.setVisible(true);
   }
   static class MyComponent extends JComponent {
    b  public void paint(Graphics g) {
         g.drawRect(20,10,100,60);
      }
   }
}

If you run this example, you will get:

Using paint() on Component
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.

Table of Contents

 About This Book

 JDK (Java Development Kit)

 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 in JDK 1.6

 JFrame Thread Behavior with JDK 8 to 20

 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

 JCheckBox - Swing Check Box Class

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

 JComboBox - Swing Combo Box 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

 AWT (Abstract Windows Toolkit)

 Integration with Desktop System

 Archived Tutorials

 References

 Full Version in PDF/EPUB