Einzelnen Beitrag anzeigen
Alt 22.02.2006, 21:35   #15 (permalink)
tele
Polsterwaffenkampfsportle r
 
Benutzerbild von tele
 

Registriert seit: 29.10.2003
Beiträge: 14.561

tele hat eine strahlende Zukunft
tele hat eine strahlende Zukunfttele hat eine strahlende Zukunfttele hat eine strahlende Zukunfttele hat eine strahlende Zukunfttele hat eine strahlende Zukunft

Standard AW: drucken eines textes in java

Für alle die an Smashs Schnipseln verzweifeln hier mal ne Tech-Demo:

Code:
/*
 * Created on 17.02.2006
 */
package printTest;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.PrintGraphics;
import java.awt.PrintJob;
import java.awt.Toolkit;
import java.io.EOFException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.Properties;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import java.awt.BorderLayout;

/**
 * @author tele
 * @version 1
 */
public class PrintTestWithGui extends JFrame {

	private static final long serialVersionUID = -8464163353847080220L;
	private JPanel jPanel = null;
	private JButton jButton = null;
	private JButton smashPrintButton = null;
	private JTextArea jTextArea = null;
	private Eventlog logger = null;
	/**
	 * This method initializes 
	 */
	public PrintTestWithGui() {
		super();
		initializeEventLog();
		initialize();
	}
	
	private void initializeEventLog() {
		logger = new Eventlog();
	}

	/**
	 * This method initializes this
	 */
	private void initialize() {
        this.setSize(new java.awt.Dimension(297,273));
        this.setContentPane(getJPanel());
        this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
        this.setTitle("Print Tester with GUI");
        this.setVisible(true);	
	}

	// --------------------------------------- GUI Getters --------------------------
	protected JFrame getJFrame() {
		return this;
	}
	/**
	 * This method initializes jPanel	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel() {
		if (jPanel == null) {
			jPanel = new JPanel();
			jPanel.setLayout(new BorderLayout());
			jPanel.add(getJButton(), java.awt.BorderLayout.NORTH);
			jPanel.add(getSmashPrintButton(), java.awt.BorderLayout.SOUTH);
			jPanel.add(getJTextArea(), java.awt.BorderLayout.CENTER);
		}
		return jPanel;
	}

	/**
	 * This method initializes jButton	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton() {
		if (jButton == null) {
			jButton = new JButton();
			jButton.setText("Print JFrame");
			jButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					action();
				}
			});
		}
		return jButton;
	}

	/**
	 * This method initializes smashPrintButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	protected JButton getSmashPrintButton() {
		if (smashPrintButton == null) {
			smashPrintButton = new JButton();
			smashPrintButton.setText("Smash's Text Print");
			smashPrintButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					doSmashPrint();
				}
			});
		}
		return smashPrintButton;
	}

	/**
	 * This method initializes jTextArea		
	 * @return javax.swing.JTextArea	
	 */
	protected JTextArea getJTextArea() {
		if (jTextArea == null) {
			jTextArea = new JTextArea();
		}
		return jTextArea;
	}

	// --------------------------------- druck Methoden ---------------------------
	
	/**
	 * this method prints the curren JFrame
	 * @return
	 */
	public boolean action() {
       Toolkit toolKit = Toolkit.getDefaultToolkit();
       Properties properties = new Properties();
       PrintJob printJob = toolKit.getPrintJob( this, "Print", properties );
       if (printJob != null) {
         System.out.println( "Auflösung des Druckers: " 
            + printJob.getPageResolution() + " dpi, Seitengröße " 
            + printJob.getPageDimension().width + " " 
            + printJob.getPageDimension().height + " DruckerName: " 
            + properties.getProperty( "awt.print.printer" ));

         System.out.println( "Properties: " );
         properties.list( System.out );
         System.getProperties().list( System.out );

         Graphics pg = printJob.getGraphics();
         if (pg != null) {
            printAll(pg);   
            pg.dispose();   
         }
         printJob.end(); 
         return true;
       }
       return false;
	}
	
	/**
	 * Smash's Print Stuff
	 */
	protected void doSmashPrint(){
		System.out.println("actionPerformed()");
		StringBuffer buffer = new StringBuffer(getJTextArea().getText());
		Properties props = new Properties();
		PrintJob pjob = getSmashPrintButton().getToolkit().getPrintJob(getJFrame(), "Cool Stuff", props);

		if (pjob != null) {
			Graphics pg = pjob.getGraphics();

			if (pg != null) {
				String s = buffer.toString();
				drucken(pjob, pg, s);
				pg.dispose();
			}
			pjob.end();
		}
	}
	
	/**
	 * eigentliche druck funktion für den text
	 * @param pjob
	 * @param pg
	 * @param s
	 */
	protected void drucken(PrintJob pjob, Graphics pg, String s) {

		int pageNum = 1;
		int linesForThisPage = 0;
		int linesForThisJob = 0;

		// Note: String is immutable so won't change while printing.
		if (!(pg instanceof PrintGraphics)) {
			throw new IllegalArgumentException("Graphics context not PrintGraphics");
		}

		StringReader sr = new StringReader(s);
		LineNumberReader lnr = new LineNumberReader(sr);
		String nextLine;
		int pageHeight = pjob.getPageDimension().height;
		int pageWidth = pjob.getPageDimension().width;
		Font helv = new Font("Helvetica", Font.PLAIN, 9);

		// have to set the font to get any output
		pg.setFont(helv);
		FontMetrics fm = pg.getFontMetrics(helv);
		int fontHeight = fm.getHeight();
		int fontDescent = fm.getDescent();
		int curHeight = 40;

		try {
			do {
				nextLine = lnr.readLine();

				if (nextLine != null) {
					if ((curHeight + fontHeight) > (pageHeight - 30)) {

						// New Page
						// Eventlog.add ("" + linesForThisPage + " lines
						// printed for page " + pageNum +"\n");
						pageNum++;
						linesForThisPage = 0;
						pg.dispose();
						pg = pjob.getGraphics();

						if (pg != null) {
							pg.setFont(helv);
						}
						curHeight = 40;
					}
					curHeight += fontHeight;
					if (pg != null) {
						String prefix = "";
						while (fm.stringWidth(nextLine) > (pageWidth - 100)) {
							while (nextLine.indexOf("\t") != -1) {
								nextLine = nextLine.replaceFirst("\t", "    ");
								prefix += "    ";
							}
							String templine = nextLine;

							while (fm.stringWidth(templine) > (pageWidth - 100)) {
								if (templine.lastIndexOf(' ') != -1) {
									templine = templine.substring(0, templine.lastIndexOf(' '));
								} else {
									templine = templine.substring(0, templine.length() - 1);
								}
							}
							pg.drawString(templine, 40, curHeight - fontDescent);
							nextLine = prefix + "  " + nextLine.substring(templine.length());
							linesForThisPage++;
							linesForThisJob++;
							curHeight += fontHeight;
						}
						pg.drawString(nextLine.replaceAll("\t", "    "), 40, curHeight - fontDescent);
						linesForThisPage++;
						linesForThisJob++;
					} else {
						logger.add("pg null" + "\n");
					}
				}
			} while (nextLine != null);
		} catch (EOFException eof) {
			logger.add(eof.toString() + "\n");
		} catch (Throwable t) {
			logger.add(t.toString() + "\n");
		}
		logger.add("" + linesForThisPage + " lines printed for page " + pageNum + "\n");
		logger.add("pages printed: " + pageNum + "\n");
		logger.add("total lines printed: " + linesForThisJob + "\n");
	}
	// ---------------------------------------------- static Methods ------------------
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new PrintTestWithGui();
	}
}  

/**
 * Eventlog
 * @author _Smash_
 * @version 1
 */
class Eventlog {

	public static StringBuffer fehler = new StringBuffer();
	public static StringBuffer log = new StringBuffer();

	// Hinzufügen eines Events

	public void add(String string) {
		fehler.append(string);
	}

	// Hinzufügen eines Logs

	public void addlog(String string) {
		log.append(string);
		System.out.print(string);
	}

	// Erzeugen der Log-Datei

	public void print() {
		try {
			PrintWriter w = new PrintWriter(new FileWriter("eventlog.txt"));

			w.print(fehler.toString().replaceAll("\n", System.getProperty("line.separator")));

			w.flush();
			w.close();
		} catch (IOException ioe) {
			;
		} // Kein Handling, da es selber die Exceptions abspeichert
	}
}
tele ist offline   Mit Zitat antworten