java.awt.print.Printableインタフェースを使った画面ハードコピー

戻る



import java.awt.*;
import java.awt.image.*;

import java.awt.event.*;
import java.awt.geom.*;
import java.awt.print.*;

import javax.swing.*;
import javax.imageio.*;

import java.io.*;

/**
* $Id: Printable.html,v 1.1 2009/06/22 16:11:52 kishi Exp kishi $
*/

public class PrintTest extends JPanel implements Printable, ActionListener {
    final static JButton button = new JButton( "印刷" );

    public PrintTest() {
        button.addActionListener( this );
    }

    public void actionPerformed( ActionEvent e ) {
        if ( e.getSource() instanceof JButton ) {
            PrinterJob printJob = PrinterJob.getPrinterJob();
            printJob.setPrintable( this );
            if ( printJob.printDialog() ) {
                try {
                    printJob.print();
                } catch ( Exception ex ) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public void paintComponent( Graphics g ) {
        super.paintComponent( g );
        Graphics2D g2 = ( Graphics2D ) g;
        drawShapes( g2 );

    }

    public void drawShapes( Graphics2D g2 ) {
        // 縁取り矩形
        g2.fill( new RoundRectangle2D.Double( 10, 10, 200, 200, 10, 10 ) );

        // 文字
        g2.setFont( new Font( "Serif" , Font.BOLD + Font.ITALIC , 30 ) );
        g2.drawString( "印字テスト", 500, 500 );

        // 静止画
        BufferedImage readImage = null;
        try {
            readImage = ImageIO.read( new File( "chicken.jpg" ) );
        } catch ( Exception e ) {
            e.printStackTrace();
            readImage = null;
        }
        if ( readImage != null ) {
            g2.drawImage( readImage, 250, 100, this );
        }

    }

    public int print( Graphics g, PageFormat pf, int pi ) throws PrinterException {
        if ( pi >= 1 ) {
            return Printable.NO_SUCH_PAGE;
        }
        drawShapes( ( Graphics2D ) g );
        return Printable.PAGE_EXISTS;
    }

    public static void main( String s[] ) {
        WindowListener l = new WindowAdapter() {
                               public void windowClosing( WindowEvent e ) {
                                   System.exit( 0 );
                               }

                               public void windowClosed( WindowEvent e ) {
                                   System.exit( 0 );
                               }
                           };
        JFrame f = new JFrame();
        f.setTitle( "Graphic2Dと印刷のテスト" );

        f.addWindowListener( l );
        JPanel panel = new JPanel();
        panel.add( button );
        f.getContentPane().add( BorderLayout.SOUTH, panel );
        f.getContentPane().add( BorderLayout.CENTER, new PrintTest() );
        f.setBounds( 0, 100, 720, 600 );
        f.setVisible( true );
    }

}
戻る inserted by FC2 system