14.2. Event and Event Source

 
[Page 430 ( continued )]

13.5. Drawing Graphics on Panels

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.

Figure 13.5. A line and a string are drawn on a panel.


Listing 13.3. TestPanelDrawing.java
(This item is displayed on pages 430 - 431 in the print version)
 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 

[Page 431]
 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 .


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net