Panels are invisible and are used as small containers that group components to achieve a desired layout. Another important use of JPanel is for drawing. You can draw things on any Swing GUI component, but normally you should use a JPanel as a canvas to draw things.
To draw in a JPanel , you create a new class that extends JPanel and overrides the paintComponent method to tell the panel how to draw things. Listing 13.3 is an example to demonstrate drawings on a panel. The example declares the NewPanel class, which extends JPanel and overrides the paintComponent method to draw a line (line 22) and a string (line 23), as shown in Figure 13.5.
1 import javax.swing.*; 2 import java.awt.Graphics; 3 4 public class TestPanelDrawing extends JFrame { 5 public TestPanelDrawing() { 6 add( new NewPanel() ); 7 } 8 9 public static void main(String[] args) { 10 TestPanelDrawing frame = new TestPanelDrawing(); 11 frame.setTitle( "TestPanelDrawing" ); 12 frame.setLocationRelativeTo( null ); // Center the frame 13 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 14 frame.setSize( 200 , 100 ); 15 frame.setVisible( true ); 16 } 17 } 18 19 class NewPanel extends JPanel { 20 protected void paintComponent(Graphics g) { 21 super .paintComponent(g); 22 g.drawLine( , , 50 , 50 ); 23 g.drawString( "Banner" , , 40 ); 24 } 25 } |
All the drawing methods have parameters that specify the locations of the subjects to be drawn. All measurements in Java are made in pixels. The string "Banner" is drawn at location (0, 40).
Note
Invoking super.paintComponent(g) (line 21) is necessary to ensure that the viewing area is cleared before a new drawing is displayed. |
Tip
Some textbooks declare a canvas class by subclassing JComponent . The problem is that you have to write the code to paint the background color if you wish to set a background in the canvas. A simple setBackground(Color color) method will not set a background color in a JComponent . |