home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / javafile / ch11 / PrintGraphics.java < prev    next >
Encoding:
Java Source  |  1998-12-14  |  2.0 KB  |  90 lines

  1. import java.awt.*;
  2. import java.awt.event.*;
  3.  
  4. public class PrintGraphics extends Frame implements ActionListener
  5. {
  6.     PrintCanvas canvas1;
  7.  
  8.     public PrintGraphics()
  9.     {
  10.         super("PrintGraphics");
  11.         canvas1 = new PrintCanvas();
  12.         add("Center", canvas1);
  13.  
  14.         Button b = new Button( "Print");
  15.         b.setActionCommand("print");
  16.         b.addActionListener(this);
  17.         add("South",b);
  18.  
  19.         pack();
  20.  
  21.     }//constructor
  22.  
  23.     public void actionPerformed(ActionEvent e)
  24.     {
  25.         String cmd = e.getActionCommand();
  26.         if (cmd.equals("print"))
  27.         {
  28.             PrintJob pjob = getToolkit().getPrintJob(this, "PrintGraphics", null);
  29. if (pjob != null)
  30.             {
  31.                 Graphics pg = pjob.getGraphics();
  32.  
  33.                 if (pg != null)
  34.                 {
  35.                     canvas1.printAll(pg);
  36.                     pg.dispose();
  37.                 }//if
  38.                 pjob.end();
  39.             }//if
  40.  
  41.         }//if
  42.  
  43.     }//actionPerformed
  44.  
  45.     public static void main(String args[])
  46.     {
  47.         PrintGraphics test = new PrintGraphics();
  48.         test.addWindowListener(new WindowCloser());
  49.         test.show();
  50.  
  51.     }
  52. }//class PrintGraphics
  53.  
  54. class PrintCanvas extends Canvas
  55. {
  56.     public Dimension getPreferredSize()
  57.     {
  58.         return new Dimension(200,200);
  59.     }
  60.  
  61.     public void paint(Graphics g)
  62.     {
  63.         Rectangle r = getBounds();
  64.  
  65.         g.setColor(Color.yellow);
  66.         g.fillRect(0,0, r.width, r.height);
  67.  
  68.         g.setColor(Color.blue);
  69.         g.drawString("Hello, World", 100, 100);
  70.  
  71.         g.setColor(Color.red);
  72.         g.drawLine(0,100,100,0);
  73.         g.fillOval(135,140,15,15);
  74.     }
  75.  
  76. }//class PrintCanvas
  77.  
  78. class WindowCloser extends WindowAdapter
  79. {
  80.     public void windowClosing(WindowEvent e)
  81.     {
  82.         Window win = e.getWindow();
  83.         win.setVisible(false);
  84.         win.dispose();
  85.         System.exit(0);
  86.     }//windowClosing
  87. }//class WindowCloser
  88.  
  89.  
  90.