Drawing Graphics - Using paint() on Frame

This section provides a tutorial example on how to override the paint() method in the javax.swing.JFrame class to draw graphics (a rectangle) on the frame window. This solution is not recommended.

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

Solution 1: You can do this very easily by extending JFrame class to create your own frame class so that you can override the paint() method. The paint() method provides you a Graphics object, which will give you utility methods to draw various types of graphics. The following sample code, JFramePaint1.java, shows you how to do this.

/* JFramePaint1.java
 * Copyright (c) 2014, HerongYang.com, All Rights Reserved.
import java.awt.*;
import javax.swing.*;
public class JFramePaint1 {
   public static void main(String[] a) {
      MyJFrame f = new MyJFrame();
      f.setTitle("Drawing Graphics in Frames");
   static class MyJFrame extends JFrame {
      public void paint(Graphics g) {

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

Note 1: The paint() method is inherited by JFrame class from the Component class. It will be called whenever this component should be painted.

Note 2: If you look at the rectangle displayed on the frame, you will see that the origin of the drawing coordinates is located at the top left corner of the entire frame, including the title bar.

Note 3: By default, the paint() method provides transparent background, in JDK 1.4, 1.5 and 1.6. This is why you see a Web page showing up in the picture.

Note 4: In JDK 1.7 and 1.8, the paint() method does not provides transparent background.

This solution is not recommended. We don't want to draw graphics in the frame bar area.

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