-1

我有下面的代码,但是当我运行它时,出现一个消息框,提示操作失败,为什么这样做以及它可以运行什么解决方案,代码应该只允许用户从 txt 文件打印

代码 :

import java.io.*;
import javax.swing.JOptionPane;
import javax.print.*;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;

public class printimg
{
    public void printimg() throws FileNotFoundException, PrintException, InterruptedException {
    String filename = ("item.text"); // THIS IS THE TEXT FILE TO PRINT
    try{
    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    DocFlavor flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_8; //  FILE IS .txt TYPE
    PrintService printService[] =
            PrintServiceLookup.lookupPrintServices(flavor, pras);
    PrintService defaultService =
            PrintServiceLookup.lookupDefaultPrintService();
    PrintService service = ServiceUI.printDialog(null, 200, 200,
            printService, defaultService, flavor, pras);
    if (service != null) {
        DocPrintJob job = service.createPrintJob();
        FileInputStream fis = new FileInputStream(filename);
        DocAttributeSet das = new HashDocAttributeSet();
        Doc doc = new SimpleDoc(fis, flavor, das);
        job.print(doc, pras);

    }
    }
    catch(Exception a){
        JOptionPane.showMessageDialog(null, "OPeration Failed");
    }
}
}

现在收到此错误:

java.lang.IllegalArgumentException: services must be non-null and non-empty
    at javax.print.ServiceUI.printDialog(ServiceUI.java:167)
    at printimg.printimg(printimg.java:20)
    at __SHELL8.run(__SHELL8.java:8)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at bluej.runtime.ExecServer$3.run(ExecServer.java:725)
4

1 回答 1

1

您看到该消息是因为代码的 try 块中的某些内容引发了异常。在 catch 块内的语句上设置断点,开始调试,并查看到底抛出了什么异常。

这将告诉您哪些代码正在破坏。从那里,您应该能够弄清楚如何解决它。

于 2012-12-21T21:41:27.063 回答