Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 12
  1. #1
    Utente di HTML.it L'avatar di pireda
    Registrato dal
    Jul 2001
    Messaggi
    654

    [Java] Stampare un file TXT

    Devo implementare in un'applicazione java la possibilità di stampare un determinato file TXT (il file di log degli errori), una volta creato il pulsante "Stampa"....Cosa devo fare?
    Maddalena... Perché proprio Iacchetti!...

  2. #2
    Utente di HTML.it
    Registrato dal
    Oct 2002
    Messaggi
    883
    salva il seguente codice in un file Print.java

    mport java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import javax.swing.*;

    /**
    * A small program to show how to print the contents of a
    * JTextArea.
    */
    public class Print extends JFrame implements ActionListener,
    Printable{
    JTextArea textArea;
    JTextPane myEditor;

    /**
    * Constructor. Set up the GUI.
    */
    public Print( JTextPane editor){
    myEditor=editor;
    pack( );
    setSize( new Dimension(300,300));
    addWindowListener( new CloseWindow( ));
    String text = myEditor.getText();
    textArea = new JTextArea( text);
    getContentPane().add( textArea, BorderLayout.CENTER);
    JButton button = new JButton( "Print");
    button.addActionListener( this);
    getContentPane().add( button, BorderLayout.SOUTH);
    show( );
    }

    /**
    * Called when the user clicks on the print button.
    */
    public void actionPerformed( ActionEvent e){
    PrinterJob printJob = PrinterJob.getPrinterJob( );
    printJob.setPrintable( this);
    if (printJob.printDialog()) {
    try {
    printJob.print( );
    }
    catch( Exception PrintException){ }
    }
    }

    /**
    * This method does the actual work - the printing.
    * It uses JTextAreas printAll(Graphics) method. If
    * n is "greater or equal to 1" then the requested
    * page does not exist. n must be 0 for the page to be
    * printed.
    * @param g - the context into which the page is
    * drawn.
    * @param f - the size and orientation of the page
    * being drawn.
    * @param n - the zero based index of the page to be
    * drawn.
    */
    public int print( Graphics g, PageFormat f, int n)
    throws PrinterException{
    if( n >= 1) {
    System.out.print( "I am in here");
    return Printable.NO_SUCH_PAGE;
    }
    System.out.println( "now I am in here");
    g.translate( 100, 100);
    textArea.printAll( g);
    return Printable.PAGE_EXISTS;
    }

    /**
    * The main method.
    */
    public static void main( String s[]){
    //new Print( myEditor);
    }
    }

    /**
    * Allow this frame to close.
    */
    class CloseWindow extends WindowAdapter{
    public void windowClosing( WindowEvent e){
    //System.exit( 0);
    }
    }

  3. #3
    Utente di HTML.it L'avatar di pireda
    Registrato dal
    Jul 2001
    Messaggi
    654
    Fatto, ma come va usato?
    Maddalena... Perché proprio Iacchetti!...

  4. #4
    Utente di HTML.it
    Registrato dal
    Oct 2002
    Messaggi
    883
    nell'azione del pulsante che deve stampare scrivi

    if (editor!=null)
    new Print(editor);

    dove editor è il pannello (non il testo!) che contiene il testo da stampare

    Io per esempio uso un JTextPane editor;

  5. #5
    Utente di HTML.it L'avatar di pireda
    Registrato dal
    Jul 2001
    Messaggi
    654
    Io sono riuscito a farlo funzionare decommentando le 2 linee alla fine (forse te le eri dimenticate) e togliendo tutti i riferimenti a myEditor (che non può essere passato dal metodo main come facevi tu perché è un metodo statico)
    Maddalena... Perché proprio Iacchetti!...

  6. #6
    Utente di HTML.it
    Registrato dal
    Oct 2002
    Messaggi
    883
    bravo!
    me li ero dimenticati

  7. #7
    Utente di HTML.it L'avatar di pireda
    Registrato dal
    Jul 2001
    Messaggi
    654
    Ho notato però che se il testo è molto lungo non mi viene stampato su più pagine, alla fine della prima la stampa si interrompe, come posso risolvere questo problema?
    Maddalena... Perché proprio Iacchetti!...

  8. #8
    Utente di HTML.it
    Registrato dal
    Oct 2002
    Messaggi
    883
    se il testo e' più lungo di una pagina il codice che ti ho postato non va bene e non so aiutarti

  9. #9
    Utente di HTML.it L'avatar di pireda
    Registrato dal
    Jul 2001
    Messaggi
    654
    AAAAAAAAHHHHHHHHRRGGGGG!!!!
    Non potevi buttarmi più giu di morale...
    Maddalena... Perché proprio Iacchetti!...

  10. #10
    Utente di HTML.it L'avatar di Angelo1974
    Registrato dal
    Feb 2003
    Messaggi
    1,107
    Prova con una di queste classi....è probabile che possa fare al tuo caso modificandola, sono sicuro che almeno 1 ritornava + di una pagina...dagli 1 occhio:
    import java.awt.print.*;
    import java.awt.*;

    public class MindPrint implements Printable
    {

    public int print(Graphics grap,
    PageFormat pageFormat, int pageIndex) throws PrinterException
    {
    if(pageIndex > 0)
    return NO_SUCH_PAGE;

    System.out.println("getImageableX == " + pageFormat.getImageableX());
    System.out.println("getImageableY == " + pageFormat.getImageableY());
    System.out.println("getImageableWidth == " + pageFormat.getImageableWidth());
    System.out.println("getImageableHeight == " + pageFormat.getImageableHeight());

    grap.drawString("Ready to roll out!", (int)pageFormat.getImageableX(),
    (int)pageFormat.getImageableY()+5);
    grap.setColor(Color.black);
    grap.drawLine((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY(),
    (int)pageFormat.getImageableWidth(), (int)pageFormat.getImageableHeight());

    return PAGE_EXISTS;

    }
    }


    import javax.swing.*;
    import java.awt.*;
    import java.awt.print.*;
    import java.awt.event.*;

    public class PrintForm extends JFrame implements Printable
    {

    public PrintForm()
    {
    setSize(200, 300);
    setTitle("PrintForm");

    JButton btn = new JButton("Print");
    btn.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    doPrint();
    }
    });

    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(BorderLayout.SOUTH, btn);

    setVisible(true);
    }

    private void doPrint()
    {
    PrinterJob pj = PrinterJob.getPrinterJob();
    if(!pj.printDialog())
    return;
    pj.setJobName("PrintForm printing self!");
    try
    {
    pj.setPrintable(this);
    pj.print();
    } catch(PrinterException ex)
    {
    System.out.println(ex);
    return;
    }
    }

    public int print(Graphics g, PageFormat pf, int index)
    {
    if(index >= 1)
    return NO_SUCH_PAGE;

    paintAll(g);
    return PAGE_EXISTS;
    }

    public static void main(String ag[])
    {
    new PrintForm().show();
    }
    }

    public class Example2 {

    //--- Private instances declarations
    private final static int POINTS_PER_INCH = 72;


    /**
    * Constructor: Example2


    *
    */
    public Example2 () {

    //--- Create a new PrinterJob object
    PrinterJob printJob = PrinterJob.getPrinterJob ();

    //--- Create a new book to add pages to
    Book book = new Book ();

    //--- Add the cover page using the default page format for this print job
    book.append (new IntroPage (), printJob.defaultPage ());

    //--- Add the document page using a landscape page format
    PageFormat documentPageFormat = new PageFormat ();
    documentPageFormat.setOrientation (PageFormat.LANDSCAPE);
    book.append (new Document (), documentPageFormat);

    //--- Tell the printJob to use the Book as the Pageable object
    printJob.setPageable (book);

    //--- Show the print dialog box. If the user clicks the
    //--- print button, we then proceed to print, else we cancel
    //--- the process.
    if (printJob.printDialog()) {
    try {
    //printJob.pageDialog(new PageFormat());
    printJob.print();
    } catch (Exception PrintException) {
    PrintException.printStackTrace();
    }
    }
    }


    /**
    * Class: IntroPage


    *
    * This class defines the painter for the cover page by implementing the
    * Printable interface.


    *
    * @author Jean-Pierre Dube <jpdube@videotron.ca>
    * @version 1.0
    * @since 1.0
    * @see Printable
    */
    private class IntroPage implements Printable {


    /**
    * Method: print


    *
    * @param g a value of type Graphics
    * @param pageFormat a value of type PageFormat
    * @param page a value of type int
    * @return a value of type int
    */
    public int print (Graphics g, PageFormat pageFormat, int page) {

    //--- Create the Graphics2D object
    Graphics2D g2d = (Graphics2D) g;

    //--- Translate the origin to 0,0 for the top left corner
    g2d.translate (pageFormat.getImageableX (), pageFormat.getImageableY ());

    //--- Set the default drawing color to black
    g2d.setPaint (Color.black);

    //--- Draw a border around the page
    Rectangle2D.Double border = new Rectangle2D.Double (0,
    0,
    pageFormat.getImageableWidth (),
    pageFormat.getImageableHeight ());
    g2d.draw (border);

    //--- Print the title
    String titleText = "Printing in Java Part 2";
    Font titleFont = new Font ("helvetica", Font.BOLD, 36);
    g2d.setFont (titleFont);

    //--- Compute the horizontal center of the page
    FontMetrics fontMetrics = g2d.getFontMetrics ();
    double titleX = (pageFormat.getImageableWidth () / 2) - (fontMetrics.stringWidth (titleText) / 2);
    double titleY = 3 * POINTS_PER_INCH;
    g2d.drawString (titleText, (int) titleX, (int) titleY);

    return (PAGE_EXISTS);
    }
    }



    /**
    * Class: Document


    *
    * This class is the painter for the document content.


    *
    *
    * @author Jean-Pierre Dube <jpdube@videotron.ca>
    * @version 1.0
    * @since 1.0
    * @see Printable
    */
    private class Document implements Printable {


    /**
    * Method: print


    *
    * @param g a value of type Graphics
    * @param pageFormat a value of type PageFormat
    * @param page a value of type int
    * @return a value of type int
    */
    public int print (Graphics g, PageFormat pageFormat, int page) {


    //--- Create the Graphics2D object
    Graphics2D g2d = (Graphics2D) g;

    //--- Translate the origin to 0,0 for the top left corner
    g2d.translate (pageFormat.getImageableX (), pageFormat.getImageableY ());
    //--- Set the drawing color to black
    g2d.setPaint (Color.black);

    //--- Draw a border around the page using a 12 point border
    g2d.setStroke (new BasicStroke (12));
    Rectangle2D.Double border = new Rectangle2D.Double (0,
    0,
    pageFormat.getImageableWidth (),
    pageFormat.getImageableHeight ());

    g2d.draw (border);

    //--- Print the text one inch from the top and left margins
    g2d.drawString ("This the content page", POINTS_PER_INCH, POINTS_PER_INCH);

    //--- Validate the page
    return (PAGE_EXISTS);

    }
    }
    public static void main (String[] args){
    Example2 e = new Example2();
    }
    } // Example2
    Se vuoi trovare l'arcobaleno, devi sopportare la pioggia

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.