פירוט התוכנית לצביעה על הנייר עם AWT
בסעיף זה מופיע פירוט מלא של התוכנית. לאחר תוכנית זו, מופיעה תוכנית הדגמה אחת נוספת הדנה בשימוש במתודה paint להדפסת רכיבי Swing.
/*File Print05.java Copyright 1998 R.G.Baldwin The purpose of this program is to demonstrate the ability to selectively print the contents of the components in an AWT container that is embedded inside another AWT container. The word selectively is used in this case to differentiate the approach to printing used in this program from the approach used in the program named Print04. That program used the printAll() method to print all of the components in a container. This program has the ability to select which components are to be printed. It also has the ability to print selected information about those components. Similar to the program named Print04, this program places one of two selectable custom Panel objects and three Button objects in a Frame. The Panel objects know how to print themselves when their overridden paint() method is invoked. One of the buttons has a listener that causes the currently selected Panel to print itself. This requires that each panel have an overridden paint() method which in turn requires that each panel be a custom panel type that extends Panel. The overridden paint() method defines the manner in which the panel prints itself. The two other buttons are used to select between the two Panels for display and printing. In other words, the user can select between two different panels and cause the one currently installed in the Frame to be printed. When the selected Panel is printed, the other components in the Frame are ignored. For purposes of illustration, one of the selectable Panel objects contains a Label, a TextField, and a Button that is not active. The other selectable Panel contains a Label, a TextField and two Button objects that are not active. The print format defined in the overridden paint() methods causes the current text from the Label and the TextField to be printed and causes the labels from the Button objects to be printed. This print format is for illustration only. Using this approach, you have total freedom to decide how to print the information associated with the components in your program. Tested using JDK 1.1.6 under Win95 **********************************************************/ import java.awt.*; import java.awt.event.*; //=======================================================// public class Print05 { public static void main(String[] args){ //instantiate a Graphical User Interface object GUI gui = new GUI(); }//end main }//end class Print05 //=======================================================// //This class is used to instantiate a Graphical User // Interface object class GUI { Frame myFrame = new Frame("Copyright 1997, R.G.Baldwin"); //The container objects referenced by areaToPrint will be // asked to print themselves. Panel areaToPrint = null; //Two selectable custom panels that can be installed // in the Frame object. Note that they are of custom // panel type MyPanelTypeX. They must be of different // types because their appearance is different and the // manner in which they print themselves is different. MyPanelType0 panel0; MyPanelType1 panel1; public GUI(){//constructor //The following button causes the container object // currently referred to by areaToPrint to print // itself. Button printButton = new Button("Print"); printButton.addActionListener( new PrintActionListener()); myFrame.add(printButton,"North"); //The following buttons are used to select different // panels for display and printing. Button selectPanel0Button = new Button("Select Panel 0"); selectPanel0Button.addActionListener( new SelectPanel0Listener()); myFrame.add(selectPanel0Button,"West"); Button selectPanel1Button = new Button("Select Panel 1"); selectPanel1Button.addActionListener( new SelectPanel1Listener()); myFrame.add(selectPanel1Button,"East"); //Construct the selectable Panels that will be assigned // to the areaToPrint reference when a selection is // made. When these panels print themselves, the print // routine causes the contents of the components in the // container to be printed. panel0 = new MyPanelType0(); panel1 = new MyPanelType1(); //Need a valid reference in areaToPrint to prevent a // null pointer exception when a selection is made and // an attempt is made to remove the old reference. areaToPrint = panel0; myFrame.setSize(340,200); myFrame.setVisible(true); //This is an anonymous inner class of the GUI class // used to terminate the program when the user closes // the Frame myFrame.addWindowListener( new WindowAdapter(){//anonymous class definition public void windowClosing(WindowEvent e){ System.exit(0);//terminate the program }//end windowClosing() }//end WindowAdapter );//end addWindowListener }//end constructor //=====================================================// //This is an inner class of the GUI class used to cause // the container referenced by areaToPrint to print // itself. This is accomplished by getting a printer // context and passing it to the overridden paint() // method for the container referenced by areaToPrint. class PrintActionListener implements ActionListener{ public void actionPerformed(ActionEvent e){ //Get a PrintJob object. This causes the system- // standard print dialog to appear. Closing the // dialog without allowing printing will return null. PrintJob myPrintJob = myFrame.getToolkit(). getPrintJob( myFrame, "Copyright R.G.Baldwin", null); if(myPrintJob != null){ //Get a graphics object for printing Graphics printGraphics = myPrintJob.getGraphics(); if(printGraphics != null){ //Invoke the custom paint() method of the // object referred to by areaToPrint passing // the PrintGraphics object as a parameter. This // will cause the object to print itself. areaToPrint.paint(printGraphics); //Cause a form feed on the printer and free // the resources tied up by the graphics object. printGraphics.dispose(); }//end if statement else System.out.println( "Didn't get print graphics object"); //End the print job and do any necessary cleanup. myPrintJob.end(); }//end if statement else System.out.println("PrintJob cancelled by user"); }//end actionPerformed() }//end class PrintActionListener //=====================================================// //This is a custom Panel class. Objects of this class // know how to print themselves when their overridden // paint() method is called and passed a PrintGraphics // object as a parameter. The format in which the // object is printed is defined in the overridden // paint() method. class MyPanelType0 extends Panel{ //These are the components in the object that contain // data to be printed. Label panel0Label; TextField panel0TextField; Button panel0Button0; //---------------------------------------------------// //This is the constructor for the custom Panel object MyPanelType0(){ panel0Label = new Label("Panel 0"); this.add(panel0Label); panel0TextField = new TextField("TextField"); this.add(panel0TextField); panel0Button0 = new Button("panel0Button0"); this.add(panel0Button0); this.setBackground(Color.yellow); }//end constructor //---------------------------------------------------// //Override paint() here. Did not attempt to handle // fontsize in order to produce pleasing output. public void paint(Graphics g){ //Separate screen painting from printer painting. // Only execute the following code if the Graphics // object is of type PrintGraphics. Otherwise, this // material would appear on the screen when the // object is painted on the screen. if(g instanceof PrintGraphics){ //This overridden version of paint() prints a // header line and then simply extracts data from // the components in the panel and prints that // data on successive lines. int leftMargin = 10;//X-position of each line int topMargin = 20;//Y-position of first line int lineIncrement = 13;//height of each line //Printing contexts do not have a default font. You // MUST set it or the system will crash under Win95 g.setFont(new Font("Serif", Font.BOLD, 18)); g.drawString("Hello from Panel 0",leftMargin, topMargin += lineIncrement); g.setFont(new Font("Serif", Font.PLAIN, 10)); g.drawString( "Contents of Label: " + panel0Label.getText(), leftMargin,topMargin += lineIncrement); g.drawString( "Contents of TextField: " + panel0TextField.getText(), leftMargin,topMargin += lineIncrement); g.drawString( "Caption on Button: " + panel0Button0.getLabel(),leftMargin, topMargin += lineIncrement); }//end if else//g is not a PrintGraphics object //Invoke the paint method of the Panel class. super.paint(g); }//end overridden paint() }//end class MyPanelType0 //=====================================================// //This is a custom Panel class. Objects of this class // know how to print themselves when their overridden // paint() method is called and passed a PrintGraphics // object as a parameter. See explanatory comments in // the definition of the class named MyPanelType0. class MyPanelType1 extends Panel{ Label panel1Label; TextField panel1TextField; Button panel1Button0; Button panel1Button1; //---------------------------------------------------// MyPanelType1(){//constructor panel1Label = new Label("Panel 1"); this.add(panel1Label); panel1TextField = new TextField("TextField"); this.add(panel1TextField); panel1Button0 = new Button("panel1Button0"); this.add(panel1Button0); panel1Button1 = new Button("panel1Button1"); this.add(panel1Button1); this.setBackground(Color.pink); }//end constructor //---------------------------------------------------// //Override paint() here. Did not attempt to handle // fontsize well and produce pleasing output. public void paint(Graphics g){ //Separate screen painting from printer painting if(g instanceof PrintGraphics){ int leftMargin = 10;//X-position of each line int topMargin = 20;//Y-position of first line int lineIncrement = 13;//height of each line //Printing contexts do not have a default font. You // must set it or the system will crash under Win95 g.setFont(new Font("Serif", Font.BOLD, 18)); g.drawString("Hello from Panel 1",leftMargin, topMargin += lineIncrement); g.setFont(new Font("Serif", Font.PLAIN, 10)); g.drawString( "Contents of Label: " + panel1Label.getText(), leftMargin,topMargin += lineIncrement); g.drawString( "Contents of TextField: " + panel1TextField.getText(),leftMargin, topMargin += lineIncrement); g.drawString( "Caption on Button: " + panel1Button0.getLabel(),leftMargin, topMargin += lineIncrement); g.drawString( "Caption on Button: " + panel1Button1.getLabel(),leftMargin, topMargin += lineIncrement); }//end if else//g is not a PrintGraphics object super.paint(g); }//end overridden paint() }//end class MyPanelType1 //=====================================================// //This is an inner class of the GUI class used to cause // panel0 to be selected for display and printing. // Obviously, this and the next class could be combined // into a single class that would use the source of the // event to determine which panel to display. class SelectPanel0Listener implements ActionListener{ public void actionPerformed(ActionEvent e){ myFrame.remove(areaToPrint); areaToPrint = panel0; myFrame.add(areaToPrint,"Center"); myFrame.invalidate();//force a redraw myFrame.setVisible(true); }//end actionPerformed() }//end class PrintActionListener //=====================================================// //This is an inner class of the GUI class used to cause // panel1 to be selected for display and printing. class SelectPanel1Listener implements ActionListener{ public void actionPerformed(ActionEvent e){ myFrame.remove(areaToPrint); areaToPrint = panel1; myFrame.add(areaToPrint,"Center"); myFrame.invalidate();//force a redraw myFrame.setVisible(true); }//end actionPerformed() }//end class PrintActionListener //=====================================================// }//end class GUI //=======================================================// |