Duvida para imprimir

eu peguei este código em um site e me falaram q funciona, mas eum não estou conseguindo entender direito alguém poderia traduzi-lo p mim???
eu queria saber se precisa criar uma classe p impressão… e se precisar criar uma classe como eu ligo essa classe ao botão que faz imprimir…

segue o código se alguém puder me ajudar agradeço:

public class printer { 

JFrame frame; 
JButton btn; 
private boolean PrintJobDone = false; 


printer(String FileToPrint, String pMode) { 

try { 



// Open the image file 
InputStream is = new BufferedInputStream(new FileInputStream(FileToPrint)); 

// Find the default service 
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; 

if (pMode != null && pMode.equalsIgnoreCase("TXT")) 
; 
else if (pMode != null && pMode.equalsIgnoreCase("PS")) 
flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT; 
else if (pMode != null && pMode.equalsIgnoreCase("PDF")) 
flavor = DocFlavor.INPUT_STREAM.PDF; 
else if (pMode != null && pMode.equalsIgnoreCase("JPG")) 
flavor = DocFlavor.INPUT_STREAM.JPEG; 
else if (pMode != null && pMode.equalsIgnoreCase("GIF")) 
flavor = DocFlavor.INPUT_STREAM.GIF; 
else if (pMode != null && pMode.equalsIgnoreCase("PNG")) 
flavor = DocFlavor.INPUT_STREAM.PNG; 
else if (pMode != null && pMode.equalsIgnoreCase("PCL")) 
flavor = DocFlavor.INPUT_STREAM.PCL; 
else if (pMode != null && pMode.equalsIgnoreCase("RAW")) 
flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; 

PrintService dservice = PrintServiceLookup.lookupDefaultPrintService(); 

PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, null); 

if (services == null || services.length < 1) 
services = PrintServiceLookup.lookupPrintServices(null, null); 

PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); 
aset.add(new Copies(1)); 
aset.add(OrientationRequested.PORTRAIT); 
aset.add(Sides.ONE_SIDED); 
aset.add(MediaSizeName.ISO_A4); 


PrintService service = ServiceUI.printDialog( 
(GraphicsConfiguration) null, 
60, 60, 
services, 
(PrintService) dservice, 
(DocFlavor) flavor, 
aset); 

if (service != null) { 

// Create the print job 
final DocPrintJob job = service.createPrintJob(); 

Doc doc = new SimpleDoc(is, flavor, null); 

// Monitor print job events; for the implementation of PrintJobWatcher, 

PrintJobWatcher pjDone = new PrintJobWatcher(job); 



try { 

// Print it 

job.print(doc, (PrintRequestAttributeSet) aset); 

} catch (PrintException e) { 
e.printStackTrace(); 
} 


// Wait for the print job to be done 
pjDone.waitForDone(); 

} 

// It is now safe to close the input stream 
is.close(); 

} catch (IOException e) { 
e.printStackTrace(); 
} catch (Exception e) { 
e.printStackTrace(); 
} finally { 

try { 

synchronized (printer.this) { 
PrintJobDone = true; 
printer.this.notify(); 
} 
} catch (Exception e) { 
e.printStackTrace(); 
} 

} 
} 


public synchronized void waitForDone() { 
try { 
while (!PrintJobDone) { 
wait(); 
} 
} catch (InterruptedException e) { 
e.printStackTrace(); 
} 
} 



class PrintJobWatcher { 

// true iff it is safe to close the print job's input stream 
boolean done = false; 

int lastEvent = 0; 


PrintJobWatcher(DocPrintJob job) { 

// Add a listener to the print job 
job.addPrintJobListener( 
new PrintJobAdapter() { 

public void printJobRequiresAttention(PrintJobEvent pje) { 
lastEvent = pje.getPrintEventType(); 
System.err.println("* Erro na Impressora:" + pje); 

} 

public void printDataTransferCompleted(PrintJobEvent pje) { 
lastEvent = pje.getPrintEventType(); 
System.err.println("* Ficheiro enviado para a Impressora "); 

} 

public void printJobCanceled(PrintJobEvent pje) { 
lastEvent = pje.getPrintEventType(); 
allDone(); 
} 


public void printJobCompleted(PrintJobEvent pje) { 
lastEvent = pje.getPrintEventType(); 
allDone(); 
} 


public void printJobFailed(PrintJobEvent pje) { 
lastEvent = pje.getPrintEventType(); 
System.err.println("* ERRO de impressão" + pje); 
// allDone(); 
} 


public void printJobNoMoreEvents(PrintJobEvent pje) { 
lastEvent = pje.getPrintEventType(); 
System.err.println("* Todos os Ficheiros foram enviados para a impressora "); 
allDone(); 
} 


void allDone() { 

synchronized (PrintJobWatcher.this) { 
done = true; 
PrintJobWatcher.this.notify(); 
} 
} 
}); 
} 


public synchronized void waitForDone() { 
try { 
while (!done) { 
wait(); 
} 
} catch (InterruptedException e) { 
e.printStackTrace(); 
} 
} 
} 

} 
} 

ou se quiserem pod me passar ujotro código mais simples e fácil de entender…
obrigado

package util;

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

public class PrintUtilities implements Printable {
  private Component componentToBePrinted;

  public static void printComponent(Component c) {
    new PrintUtilities(c).print();
  }
  
  public PrintUtilities(Component componentToBePrinted) {
    this.componentToBePrinted = componentToBePrinted;
  }
  
  public void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if (printJob.printDialog())
      try {
        printJob.print();
      } catch(PrinterException pe) {
        System.out.println("Error printing: " + pe);
      }
  }

  public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
      return(NO_SUCH_PAGE);
    } else {
      Graphics2D g2d = (Graphics2D)g;
      g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
      disableDoubleBuffering(componentToBePrinted);
      componentToBePrinted.paint(g2d);
      enableDoubleBuffering(componentToBePrinted);
      return(PAGE_EXISTS);
    }
  }

  public static void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
  }

  public static void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);
  }
}

Só da um PrintUtilities.print(Component); // você passa um JFrame ou JPanel ou Button ou etc(um Component)

eu tenho q cria uma nova classe p por esse cod dentro ou ele vai ond???

Crie a classe PrintUtilities se quiser pra poder imprimir qualquer coisa

dai por exemplo você tem a classe clienteFrame que extends JFrame
dai você pode criar um botao com esse Listener

button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ PrintUtilities.print(this);//clienteFrame extend JFrame então ele é um Component } });

[quote=Mark_Ameba]Crie a classe PrintUtilities se quiser pra poder imprimir qualquer coisa

dai por exemplo você tem a classe clienteFrame que extends JFrame
dai você pode criar um botao com esse Listener

button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ PrintUtilities.print(this);//clienteFrame extend JFrame então ele é um Component } });[/quote]
imprimir como? imprimir na tela? mandar para a impressora???

Vai abrir tela pra escolhe a impressora dai aperta pra imprimi, e vai imprimi -.~
(Nao testei em linux)

button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
clienteFrame extend JFrame então ele é um Component
}
});

esse cod eu tenho q dexa assim mesmo ou tenho q mudar algo??? pq assim da erro noPrintUtilities.print(this);

tem q te algum drive??

Não precisa de Driver nenhum só isso mesmo

button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ PrintUtilities.print(this); //ou se quiser new PrintUtilities(this).print(); } });

Pessoal,
Estou chamando o método citado, passando um jPanel, escolho a impressora mas estou tendo 2 problemas diferentes em impressoras diferentes
em uma estou pegando o erro

" java.awt.print.PrinterException: Acesso negado."

e na outra

1º erro:
Acesso negado??? pq? consigo imprimir normalmente por outros app…
2º erro:
Tentei reinicia o serviço do spooler, mas nada adiantou…

alguma ideia??
valeuuuu