Java Swing Tutorials - Herong's Tutorial Examples - v4.31, by Herong Yang
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) 1997-2018 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:
Note: The content pane is replaced by a new component object we created with our own the paint() method.
Table of Contents
Introduction of Java Swing Package
Graphics Environment of the Local System
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 12
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
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
JEditorPane - The Editor Pane Class
SwingWorker - The Background Task Worker
AWT (Abstract Windows Toolkit)