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) 2002 by Dr. Herong Yang, http://www.herongyang.com/
*/
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 {
public void paint(Graphics g) {
g.drawRect(20,10,100,60);
}
}
}
If you run this example, you will get:
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, 1.5.0. and 1.6.0