我该如何解决这个错误?

时间:2011-07-06 04:18:04

标签: java printing

// Program to print simple text on a Printer

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

class Printer extends JPanel implements Printable  {

JButton print;

Printer() {
 buildGUI();
 hookUpEvents();
}

public void buildGUI() {
  JFrame fr = new JFrame("Program to Print on a Printer");
  JPanel p = new JPanel();
  print = new JButton("Print");
  setPreferredSize( new Dimension ( 200,200 ) );
  p.setBackground( Color.black );
  fr.add(p);
  p.add( print , BorderLayout.CENTER );
  fr.pack();
  fr.setVisible( true );
}

public void hookUpEvents() {
 print.addActionListener( new ActionListener() {
   public void actionPerformed( ActionEvent ae ) {
      PrinterJob job = PrinterJob.getPrinterJob();
      job.setPrintable( new Printer() );
      boolean doPrint = job.printDialog();
       if( doPrint ) {
           try {
            job.print();
           }  catch( PrinterException exc) {
                System.out.println( exc );
              }
       }  else {
            System.out.println("You cancelled the print");
          } 
   }
 });
}

public static void main( String args[] ) {
  new Printer();
}
}

编译代码时出现以下错误:

Printer.java:9: Printer is not abstract and does not override abstract method   print(Graphics,PageFormat,int) in Printable
 class Printer extends JPanel implements Printable  {

^       1错误

如何解决此错误?

1 个答案:

答案 0 :(得分:2)

@Suhail:我想你需要实现Printable接口: -

class Printer extends JPanel implements java.awt.print.Printable

并添加方法: -

public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)