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) 2002 by Dr. Herong Yang, http://www.herongyang.com/
*/
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.
Sample programs listed in this section have been tested with JDK 1.4.2, 1.5.0. and 1.6.0