תוכנית הדגמה לצביעה על הנייר עם Swing
זו גירסת ה- Swing של התוכנית המכונה Print05.java.
השינויים המשמעותיים היחידים הנחוצים כדי להמיר את Print05 לגירסת Swing זו הם:
· החלפת כל רכיבי ה- AWT (כגון Button) ברכיבי Swing (כגון JButton)
· החלת הפעלת המתודה getContent Pannel() על כל הפעולות המטפלות באותה שכבה ב- Jframe שבה שוכנים הרכיבים.
מלבד זאת, תוכנית זו בעיקרה זהה לתוכנית הקודמת המכונה Print05, ולכן לא נדון בה מעבר לכך.
פירוט תוכנית לצביעה על הנייר עם Swing
סעיף זה מציג פירוט מלא של התוכנית.
/*File Print06.java Copyright 1998 R.G.Baldwin This is a Swing version of the program named Print05.java. The only significant modifications required to convert Print05 to this Swing version was to replace all the AWT components (such as Button) with Swing components (such as JButton), and then to apply the getContentPane() method invocation to all operations that deal with the layer in the JFrame where the components reside. The purpose of this program is to demonstrate the ability to selectively print the contents of Swing components in a Swing container that is embedded inside another Swing 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 JPanel objects and three JButton objects in a JFrame. The JPanel 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 JPanel 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 JPanel. The overridden paint() method defines the manner in which the panel prints itself. The two other buttons are used to select between the two JPanel objects for display and printing. In other words, the user can select between two different panels and cause the one currently installed in the JFrame to be printed. When the selected JPanel is printed, the other components in the JFrame are ignored. For purposes of illustration, one of the selectable JPanel objects contains a JLabel, a JTextField, and a JButton that is not active. The other selectable JPanel contains a JLabel, a JTextField and two JButton objects that are not active. The print format defined in the overridden paint() methods causes the current text from the JLabel and the JTextField to be printed and causes the captions from the JButton 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 and Swing 1.0.1 under Win95 **********************************************************/ import java.awt.*; import java.awt.event.*; import com.sun.java.swing.*; //=======================================================// public class Print06 { public static void main(String[] args){ //instantiate a Graphical User Interface object GUI gui = new GUI(); }//end main }//end class Print06 //=======================================================// //This class is used to instantiate a Graphical User // Interface object class GUI { JFrame myFrame = new JFrame("Copyright 1997, R.G.Baldwin"); //The container objects referenced by areaToPrint will be // asked to print themselves. JPanel areaToPrint = null; //Two selectable custom panels that can be installed // in the JFrame 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. JButton printButton = new JButton("Print"); printButton.addActionListener( new PrintActionListener()); myFrame.getContentPane().add(printButton,"North"); //The following buttons are used to select different // panels for display and printing. JButton selectPanel0Button = new JButton("Select JPanel 0"); selectPanel0Button.addActionListener( new SelectPanel0Listener()); myFrame.getContentPane().add(selectPanel0Button,"West"); JButton selectPanel1Button = new JButton("Select JPanel 1"); selectPanel1Button.addActionListener( new SelectPanel1Listener()); myFrame.getContentPane().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(400,200); myFrame.setVisible(true); //This is an anonymous inner class of the GUI class // used to terminate the program when the user closes // the JFrame 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 contrainer 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 JPanel 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 JPanel{ //These are the components in the object that contain // data to be printed. JLabel panel0Label; JTextField panel0TextField; JButton panel0Button0; //---------------------------------------------------// //This is the constructor for the custom JPanel object MyPanelType0(){ panel0Label = new JLabel("JPanel 0"); this.add(panel0Label); panel0TextField = new JTextField("JTextField"); this.add(panel0TextField); panel0Button0 = new JButton("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 JPanel 0",leftMargin, topMargin += lineIncrement); g.setFont(new Font("Serif", Font.PLAIN, 10)); g.drawString( "Contents of JLabel: " + panel0Label.getText(), leftMargin,topMargin += lineIncrement); g.drawString( "Contents of JTextField: " + panel0TextField.getText(), leftMargin,topMargin += lineIncrement); g.drawString( "Caption on JButton: " + panel0Button0.getText(),leftMargin, topMargin += lineIncrement); }//end if else//g is not a PrintGraphics object //Invoke the paint method of the JPanel class. super.paint(g); }//end overridden paint() }//end class MyPanelType0 //=====================================================// //This is a custom JPanel 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 JPanel{ JLabel panel1Label; JTextField panel1TextField; JButton panel1Button0; JButton panel1Button1; //---------------------------------------------------// MyPanelType1(){//constructor panel1Label = new JLabel("JPanel 1"); this.add(panel1Label); panel1TextField = new JTextField("JTextField"); this.add(panel1TextField); panel1Button0 = new JButton("panel1Button0"); this.add(panel1Button0); panel1Button1 = new JButton("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 JPanel 1",leftMargin, topMargin += lineIncrement); g.setFont(new Font("Serif", Font.PLAIN, 10)); g.drawString( "Contents of JLabel: " + panel1Label.getText(), leftMargin,topMargin += lineIncrement); g.drawString( "Contents of JTextField: " + panel1TextField.getText(),leftMargin, topMargin += lineIncrement); g.drawString( "Caption on JButton: " + panel1Button0.getText(),leftMargin, topMargin += lineIncrement); g.drawString( "Caption on JButton: " + panel1Button1.getText(),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.getContentPane().remove(areaToPrint); areaToPrint = panel0; myFrame.getContentPane().add(areaToPrint,"Center"); myFrame.getContentPane().invalidate(); myFrame.setVisible(true); myFrame.repaint(); }//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.getContentPane().remove(areaToPrint); areaToPrint = panel1; myFrame.getContentPane().add(areaToPrint,"Center"); myFrame.getContentPane().invalidate(); myFrame.setVisible(true); myFrame.repaint(); }//end actionPerformed() }//end class PrintActionListener //=====================================================// }//end class GUI //=======================================================// |