/* Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com
This code is for educational purposes only. Use at own risk.*/

1. import javax.swing.*; 

2. import java.awt.*; 

3. import java.awt.event.*; 

4. import java.awt.print.*; 

5.  

6. public class Printing 

7.       extends JFrame 

8.       implements Printable 

9.               , ActionListener 

10.

11.   JButton btn ; 

12.   JTextArea ta ; 

13.  

14.   public void 

15.   actionPerformed ( ActionEvent ev ) 

16.   { 

17.     PrinterJob pj = PrinterJob.getPrinterJob() ; 

18.  

19.     pj.setPrintable ( this ) ; 

20.  

21.     boolean doit = pj.printDialog () ; 

22.  

23.     if ( ! doit ) return

24.     try 

25.     { 

26.       pj.print () ; 

27.       ta.append ( "==== FINITO ====" ) ; 

28.     } 

29.     catch ( Exception e ) 

30.     { 

31.       System.out.println ( "Can't print : "  + e ) ; 

32.     } 

33.   } 

34.   public int 

35.   print ( Graphics gr, PageFormat pf, int pg ) 

36.     throws PrinterException 

37.   { 

38.     if ( pg != 0 )  return Printable.NO_SUCH_PAGE

39.  

40.     gr.setFont ( new Font ( "Serif", Font.PLAIN, 16 ) ) ; 

41.     gr.setColor( Color.black ); 

42.  

43.     int x = 0 ; int y = 0

44.     for ( int i=0; i < 20; i++ ) 

45.     { 

46.       gr.drawString ( "that's printed at " + x + " " + y, 

47.         x, y ) ; 

48.       x += 25  ; y += 25

49.     } 

50.  

51.     x =  (int) pf.getImageableX() ; 

52.     y =  (int) pf.getImageableY() ; 

53.     int w =  (int) pf.getImageableWidth() ; 

54.     int h =  (int) pf.getImageableHeight() ; 

55.  

56.     gr.drawRect ( x, y, w, h ); 

57.  

58.     for ( int i=x ; i < w/2+x ; i+=20

59.     { 

60.       gr.drawLine ( x, y, i, h/2+y ); 

61.     } 

62.  

63.     ta.append ( "Page : " + pg  + "\n\n" ) ; 

64.     ta.append ( "Left-top : " ) ; 

65.     ta.append ( pf.getImageableX()  + "  " ) ; 

66.     ta.append ( pf.getImageableY()  + "\n\n" ) ; 

67.  

68.     ta.append ( "Width & height : " ) ; 

69.     ta.append ( pf.getImageableWidth() + "  " ) ; 

70.     ta.append ( pf.getImageableHeight()  + "\n" ) ; 

71.     ta.append ( "=====================\n" ) ; 

72.  

73.     return Printable.PAGE_EXISTS

74.   } 

75.  

76.   public 

77.   Printing () 

78.   { 

79.     setSize(400,300); 

80.     btn = new JButton ( "Don't believe everything" ) ; 

81.     btn.addActionListener ( this ) ; 

82.     ta = new JTextArea ( 14,40 ) ; 

83.     Container cp = getContentPane(); 

84.     cp.setLayout( new FlowLayout() ); 

85.     cp.add ( btn ) ; 

86.     cp.add ( ta ) ; 

87.     addWindowListener( 

88.       new WindowAdapter() 

89.       { 

90.        public void windowClosing(WindowEvent ev) 

91.        { System.exit(0);  } 

92.       } 

93.     ); 

94.   } 

95.   public static void main (String[] a) 

96.   { 

97.     (new Printing()).setVisible(true); 

98.   } 

99.