ContainerPrintable: Unterschied zwischen den Versionen

Aus Byte-Welt Wiki
Zur Navigation springenZur Suche springen
K
 
(14 dazwischenliegende Versionen von 2 Benutzern werden nicht angezeigt)
Zeile 1: Zeile 1:
<code=java>
+
__TOC__
 +
 
 +
== Beschreibung ==
 +
 
 +
Wir können den zu druckenden Container im Konstruktor der Klasse "ContainerPrintable" übergeben.
 +
 
 +
Das Drucken geschieht in Segmenten, die eine Höhe von 10 haben.
 +
 
 +
Wir können die Segmenthöhe mit der Methode setSegmentHeight(..) anpassen.
 +
 
 +
Wir können das eigentliche Drucken über eine der ContainerPrintable.print(..) Methoden veranlassen.
 +
 
 +
Wenn '''kein''' Printdialog erwünscht ist, rufen wir ContainerPrintable.setPrintDialog(false) auf
 +
bevor wir eine der ContainerPrintable.print(..) Methoden aufrufen.
 +
 
 +
Die Klasse "ContainerPrintableDemo" zeigt ein Anwendungsbeispiel:
 +
 
 +
[[Datei:ContainerPrintableDemo.jpg]]
 +
 
 +
Das Druckbild sieht so aus (zwei Seiten):
 +
 
 +
[[Datei:ContainerPrintableDemo2.jpg]]
 +
 
 +
== Quellcode ==
 +
 
 +
<syntaxhighlight lang="java">
 
/*
 
/*
 
  * ContainerPrintable.java
 
  * ContainerPrintable.java
Zeile 5: Zeile 30:
 
  * The printing is done in segments of height 10.
 
  * The printing is done in segments of height 10.
 
  * We can adapt the segment height using method setSegmentHeight(..)
 
  * We can adapt the segment height using method setSegmentHeight(..)
 +
*
 +
* We can do the actual printing by calling one of the ContainerPrintable.print(..) methods.
 +
* If no print dialog is desired, we call ContainerPrintable.setPrintDialog(false)
 +
* before calling one of the ContainerPrintable.print(..) methods.
 
  */
 
  */
 
 
import java.awt.*;
 
import java.awt.*;
 
import java.awt.print.*;
 
import java.awt.print.*;
 
import java.awt.geom.*;
 
import java.awt.geom.*;
 
+
import java.util.logging.*;
 +
import javax.print.attribute.*;
 +
import javax.print.attribute.standard.*;
 +
 
public class ContainerPrintable implements Printable {
 
public class ContainerPrintable implements Printable {
 
+
 
     private Container container;//The container to print
 
     private Container container;//The container to print
 
     private int segmentHeight = 10;//The container's segment height
 
     private int segmentHeight = 10;//The container's segment height
Zeile 20: Zeile 51:
 
     private final Rectangle clip = new Rectangle(0, 0, 0, 0);//To store an area to be printed
 
     private final Rectangle clip = new Rectangle(0, 0, 0, 0);//To store an area to be printed
 
     private final Rectangle tempRect = new Rectangle(0, 0, 0, 0);
 
     private final Rectangle tempRect = new Rectangle(0, 0, 0, 0);
 
+
    static private PrintRequestAttributeSet attr;
 +
    private static boolean printDialog = true;
 +
 
     public ContainerPrintable(final Container container) {
 
     public ContainerPrintable(final Container container) {
 
         this.container = container;
 
         this.container = container;
Zeile 26: Zeile 59:
 
         totalWidth = container.getWidth();
 
         totalWidth = container.getWidth();
 
     }
 
     }
 
+
 +
    @Override
 
     public int print(final Graphics graphics, final PageFormat pageFormat, final int pageIndex)
 
     public int print(final Graphics graphics, final PageFormat pageFormat, final int pageIndex)
 
             throws PrinterException {
 
             throws PrinterException {
Zeile 65: Zeile 99:
 
         if (scaleFactor != 1.0D) {
 
         if (scaleFactor != 1.0D) {
 
             g2d.scale(scaleFactor, scaleFactor);
 
             g2d.scale(scaleFactor, scaleFactor);
        // otherwise, ensure that the current portion of the container is centered horizontally
+
            // otherwise, ensure that the current portion of the container is centered horizontally
 
         } else {
 
         } else {
 
             int diff = (imgWidth - clip.width) / 2;
 
             int diff = (imgWidth - clip.width) / 2;
Zeile 82: Zeile 116:
 
         return PAGE_EXISTS;
 
         return PAGE_EXISTS;
 
     }
 
     }
 
+
 
     private int getSegmentCount() {
 
     private int getSegmentCount() {
         return container.getHeight() / segmentHeight;
+
         int height = container.getHeight();
 +
        int count = height / segmentHeight;
 +
        if (count * segmentHeight < height) {
 +
            count++;
 +
        }
 +
        return count;
 
     }
 
     }
 
+
 
     public void setSegmentHeight(final int segmentHeight) {
 
     public void setSegmentHeight(final int segmentHeight) {
 
         this.segmentHeight = segmentHeight;
 
         this.segmentHeight = segmentHeight;
 
     }
 
     }
 
+
 
     public int getSegmentHeight() {
 
     public int getSegmentHeight() {
 
         return segmentHeight;
 
         return segmentHeight;
 
     }
 
     }
 
+
 +
    public static void setPrintDialog(boolean printDialog) {
 +
        ContainerPrintable.printDialog = printDialog;
 +
    }
 +
 +
    public static boolean isPrintDialog() {
 +
        return printDialog;
 +
    }
 +
 
     private void nextClip(final int pageHeight) {
 
     private void nextClip(final int pageHeight) {
 
         clip.x = 0;
 
         clip.x = 0;
Zeile 103: Zeile 150:
 
         do {
 
         do {
 
             clip.height += segmentHeight;
 
             clip.height += segmentHeight;
             if (++segment >= segmentCount) {
+
            segment++;
 +
             if (segment >= segmentCount) {
 
                 break;
 
                 break;
 
             }
 
             }
Zeile 109: Zeile 157:
 
         clip.width = totalWidth;
 
         clip.width = totalWidth;
 
     }
 
     }
}
+
   
</code=java>
+
     static public void print(final Printable printable) {
<code=java>
 
/*
 
* ContainerPrintableDemo.java
 
*
 
  */
 
 
 
import java.awt.*;
 
import java.awt.event.*;
 
import java.awt.print.*;
 
import javax.print.attribute.*;
 
import javax.print.attribute.standard.*;
 
import javax.swing.*;
 
import utils.ContainerPrintable;
 
 
 
public class ContainerPrintableDemo extends JFrame {
 
 
 
    private JButton btPrint;
 
    private JColorChooser colorChooser;
 
    private PrintRequestAttributeSet attr;
 
 
 
    public ContainerPrintableDemo() {
 
        super("ContainerPrintableDemo");
 
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
 
        btPrint = new JButton("Print...");
 
        colorChooser = new JColorChooser();
 
        btPrint.addActionListener(new ActionListener() {
 
 
 
            public void actionPerformed(ActionEvent evt) {
 
                print(new ContainerPrintable(colorChooser));
 
            }
 
        });
 
        getContentPane().add(btPrint, BorderLayout.PAGE_START);
 
        getContentPane().add(colorChooser, BorderLayout.CENTER);
 
        pack();
 
        setLocationRelativeTo(null);
 
    }
 
 
 
     public void print(final Printable printable) {
 
 
         print(printable, true);
 
         print(printable, true);
 
     }
 
     }
 
+
     public void print(final Printable printable, final boolean portrait) {
+
     static public void print(final Printable printable, final boolean portrait) {
 
         print(printable, portrait, new Insets(10, 10, 10, 10));
 
         print(printable, portrait, new Insets(10, 10, 10, 10));
 
     }
 
     }
 
+
     public void print(final Printable printable, final boolean portrait, final Insets insets) {
+
     static public void print(final Printable printable, final boolean portrait,
 +
            final Insets insets) {
 
         PrinterJob pjob = PrinterJob.getPrinterJob();
 
         PrinterJob pjob = PrinterJob.getPrinterJob();
 
         pjob.setPrintable(printable);
 
         pjob.setPrintable(printable);
Zeile 184: Zeile 195:
 
                     (mediaHeight - topMargin - bottomMargin), Size2DSyntax.MM));
 
                     (mediaHeight - topMargin - bottomMargin), Size2DSyntax.MM));
 
         }
 
         }
         if (pjob.printDialog(attr)) {
+
        boolean dialogOk = true;
 +
         if (printDialog) {
 +
            dialogOk = pjob.printDialog(attr);
 +
        }
 +
        if (dialogOk) {
 
             try {
 
             try {
 
                 pjob.print(attr);
 
                 pjob.print(attr);
 
             } catch (PrinterException ex) {
 
             } catch (PrinterException ex) {
                 ex.printStackTrace();
+
                 Logger.getLogger(ContainerPrintable.class.getName()).log(Level.SEVERE, null, ex);
 
             }
 
             }
 
         }
 
         }
 
     }
 
     }
 +
}
 +
</syntaxhighlight>
 +
<syntaxhighlight lang="java">
 +
/*
 +
* ContainerPrintableDemo.java
 +
*
 +
*/
 +
 +
import java.awt.*;
 +
import java.awt.event.*;
 +
import javax.swing.*;
 +
 +
public class ContainerPrintableDemo {
 +
    private final JPanel testPanel = new JPanel(new GridLayout(0, 1));
 +
   
 +
    public ContainerPrintableDemo() {
 +
       
 +
        JFrame f = new JFrame("ContainerPrintableDemo");
 +
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
 +
       
 +
        JButton btPrint = new JButton("Print");
 +
        btPrint.addActionListener(new ActionListener() {
 +
 +
            @Override
 +
            public void actionPerformed(final ActionEvent evt) {
 +
                ContainerPrintable containerPrintable = new ContainerPrintable(testPanel);
 +
                containerPrintable.setSegmentHeight(testPanel.getComponent(0).getSize().height);
 +
                ContainerPrintable.print(containerPrintable);
 +
            }
 +
        });
  
 +
        JButton btClose = new JButton("Close");
 +
        btClose.addActionListener(new ActionListener() {
 +
 +
            @Override
 +
            public void actionPerformed(final ActionEvent evt) {
 +
                f.dispose();
 +
            }
 +
        });
 +
 +
        JPanel actionPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
 +
        actionPanel.add(btClose);
 +
        actionPanel.add(btPrint);
 +
        f.add(actionPanel, BorderLayout.PAGE_END);
 +
 +
   
 +
        for (int i = 0; i < 60; i++) {
 +
            testPanel.add(new JLabel("TEST " + i));
 +
        }
 +
        f.add(new JScrollPane(testPanel), BorderLayout.CENTER);
 +
        f.setSize(400, 600);
 +
        f.setLocationRelativeTo(null);
 +
        f.setVisible(true);
 +
    }
 +
 
     public static void main(final String[] args) {
 
     public static void main(final String[] args) {
 
         Runnable gui = new Runnable() {
 
         Runnable gui = new Runnable() {
 
+
 +
            @Override
 
             public void run() {
 
             public void run() {
                 new ContainerPrintableDemo().setVisible(true);
+
                 new ContainerPrintableDemo();
 
             }
 
             }
 
         };
 
         };
Zeile 204: Zeile 274:
 
     }
 
     }
 
}
 
}
</code=java>
+
 
[[Kategorie:Java]]
+
</syntaxhighlight>
 +
 
 
[[Kategorie:Swing]]
 
[[Kategorie:Swing]]
 
[[Kategorie:Java-Codeschnipsel]]
 
[[Kategorie:Java-Codeschnipsel]]

Aktuelle Version vom 13. November 2021, 14:23 Uhr

Inhaltsverzeichnis

Beschreibung

Wir können den zu druckenden Container im Konstruktor der Klasse "ContainerPrintable" übergeben.

Das Drucken geschieht in Segmenten, die eine Höhe von 10 haben.

Wir können die Segmenthöhe mit der Methode setSegmentHeight(..) anpassen.

Wir können das eigentliche Drucken über eine der ContainerPrintable.print(..) Methoden veranlassen.

Wenn kein Printdialog erwünscht ist, rufen wir ContainerPrintable.setPrintDialog(false) auf bevor wir eine der ContainerPrintable.print(..) Methoden aufrufen.

Die Klasse "ContainerPrintableDemo" zeigt ein Anwendungsbeispiel:

ContainerPrintableDemo.jpg

Das Druckbild sieht so aus (zwei Seiten):

ContainerPrintableDemo2.jpg

Quellcode

/*
 * ContainerPrintable.java
 * We can pass the container to be printed in the constructor.
 * The printing is done in segments of height 10.
 * We can adapt the segment height using method setSegmentHeight(..)
 * 
 * We can do the actual printing by calling one of the ContainerPrintable.print(..) methods.
 * If no print dialog is desired, we call ContainerPrintable.setPrintDialog(false)
 * before calling one of the ContainerPrintable.print(..) methods.
 */
import java.awt.*;
import java.awt.print.*;
import java.awt.geom.*;
import java.util.logging.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
 
public class ContainerPrintable implements Printable {
 
    private Container container;//The container to print
    private int segmentHeight = 10;//The container's segment height
    private int totalWidth;//To save total width.
    private int last = -1;//The most recent page index asked to print
    private int segment = 0;//The next segment to print
    private final Rectangle clip = new Rectangle(0, 0, 0, 0);//To store an area to be printed
    private final Rectangle tempRect = new Rectangle(0, 0, 0, 0);
    static private PrintRequestAttributeSet attr;
    private static boolean printDialog = true;
 
    public ContainerPrintable(final Container container) {
        this.container = container;
        container.setBackground(Color.WHITE);
        totalWidth = container.getWidth();
    }
 
    @Override
    public int print(final Graphics graphics, final PageFormat pageFormat, final int pageIndex)
            throws PrinterException {
        final int imgWidth = (int) pageFormat.getImageableWidth();
        final int imgHeight = (int) pageFormat.getImageableHeight();
        if (imgWidth <= 0) {
            throw new PrinterException("Width of printable area is too small.");
        }
        // the amount of vertical space available for printing the container
        int availableSpace = imgHeight;
        if (availableSpace <= 0) {
            throw new PrinterException("Height of printable area is too small.");
        }
        // we need a scale factor to fit the container's entire width on the page
        double scaleFactor = 1.0D;
        if (totalWidth > imgWidth) {
            scaleFactor = (double) imgWidth / (double) totalWidth;
        }
        while (last < pageIndex) {
            if (segment >= getSegmentCount()) {// if we are finished with all segments
                return NO_SUCH_PAGE;
            }
            int scaledHeight = (int) (availableSpace / scaleFactor);
            // calculate the area of the container to be printed for this page
            nextClip(scaledHeight);
            last++;
        }
        // translate into the coordinate system of the pageFormat
        Graphics2D g2d = (Graphics2D) graphics;
        g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
        // constrain the container output to the available space
        tempRect.x = 0;
        tempRect.y = 0;
        tempRect.width = imgWidth;
        tempRect.height = availableSpace;
        g2d.clip(tempRect);
        // if we have a scale factor, scale the graphics object to fit the entire width
        if (scaleFactor != 1.0D) {
            g2d.scale(scaleFactor, scaleFactor);
            // otherwise, ensure that the current portion of the container is centered horizontally
        } else {
            int diff = (imgWidth - clip.width) / 2;
            g2d.translate(diff, 0);
        }
        // store the old transform and clip for later restoration
        AffineTransform oldTrans = g2d.getTransform();
        Shape oldClip = g2d.getClip();
        // print the current section of the container
        g2d.translate(-clip.x, -clip.y);
        g2d.clip(clip);
        container.print(g2d);
        // restore the original transform and clip
        g2d.setTransform(oldTrans);
        g2d.setClip(oldClip);
        return PAGE_EXISTS;
    }
 
    private int getSegmentCount() {
        int height = container.getHeight();
        int count = height / segmentHeight;
        if (count * segmentHeight < height) {
            count++;
        }
        return count;
    }
 
    public void setSegmentHeight(final int segmentHeight) {
        this.segmentHeight = segmentHeight;
    }
 
    public int getSegmentHeight() {
        return segmentHeight;
    }
 
    public static void setPrintDialog(boolean printDialog) {
        ContainerPrintable.printDialog = printDialog;
    }
 
    public static boolean isPrintDialog() {
        return printDialog;
    }
 
    private void nextClip(final int pageHeight) {
        clip.x = 0;
        clip.y += clip.height;// adjust clip to the top of the next set of segments
        clip.height = 0;// adjust clip height to be zero
        // fit as many segments as possible, and at least one
        int segmentCount = getSegmentCount();
        do {
            clip.height += segmentHeight;
            segment++;
            if (segment >= segmentCount) {
                break;
            }
        } while (clip.height + segmentHeight <= pageHeight);
        clip.width = totalWidth;
    }
 
    static public void print(final Printable printable) {
        print(printable, true);
    }
 
    static public void print(final Printable printable, final boolean portrait) {
        print(printable, portrait, new Insets(10, 10, 10, 10));
    }
 
    static public void print(final Printable printable, final boolean portrait,
            final Insets insets) {
        PrinterJob pjob = PrinterJob.getPrinterJob();
        pjob.setPrintable(printable);
        // create an attribute set to store attributes from the print dialog
        if (attr == null) {
            attr = new HashPrintRequestAttributeSet();
            float leftMargin = insets.left;
            float rightMargin = insets.right;
            float topMargin = insets.top;
            float bottomMargin = insets.bottom;
            if (portrait) {
                attr.add(OrientationRequested.PORTRAIT);
            } else {
                attr.add(OrientationRequested.LANDSCAPE);
                leftMargin = insets.top;
                rightMargin = insets.bottom;
                topMargin = insets.right;
                bottomMargin = insets.left;
            }
            attr.add(MediaSizeName.ISO_A4);
            MediaSize mediaSize = MediaSize.ISO.A4;
            float mediaWidth = mediaSize.getX(Size2DSyntax.MM);
            float mediaHeight = mediaSize.getY(Size2DSyntax.MM);
            attr.add(new MediaPrintableArea(
                    leftMargin, topMargin,
                    (mediaWidth - leftMargin - rightMargin),
                    (mediaHeight - topMargin - bottomMargin), Size2DSyntax.MM));
        }
        boolean dialogOk = true;
        if (printDialog) {
            dialogOk = pjob.printDialog(attr);
        }
        if (dialogOk) {
            try {
                pjob.print(attr);
            } catch (PrinterException ex) {
                Logger.getLogger(ContainerPrintable.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
/*
 * ContainerPrintableDemo.java
 *
 */
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class ContainerPrintableDemo {
    private final JPanel testPanel = new JPanel(new GridLayout(0, 1));
    
    public ContainerPrintableDemo() {
        
        JFrame f = new JFrame("ContainerPrintableDemo");
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        JButton btPrint = new JButton("Print");
        btPrint.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(final ActionEvent evt) {
                ContainerPrintable containerPrintable = new ContainerPrintable(testPanel);
                containerPrintable.setSegmentHeight(testPanel.getComponent(0).getSize().height);
                ContainerPrintable.print(containerPrintable);
            }
        });

        JButton btClose = new JButton("Close");
        btClose.addActionListener(new ActionListener() {
 
            @Override
            public void actionPerformed(final ActionEvent evt) {
                f.dispose();
            }
        });

        JPanel actionPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        actionPanel.add(btClose);
        actionPanel.add(btPrint);
        f.add(actionPanel, BorderLayout.PAGE_END);

    
        for (int i = 0; i < 60; i++) {
            testPanel.add(new JLabel("TEST " + i));
        }
        f.add(new JScrollPane(testPanel), BorderLayout.CENTER);
        f.setSize(400, 600);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
 
    public static void main(final String[] args) {
        Runnable gui = new Runnable() {
 
            @Override
            public void run() {
                new ContainerPrintableDemo();
            }
        };
        //GUI must start on EventDispatchThread:
        SwingUtilities.invokeLater(gui);
    }
}