我正在使用Java的Swing创建一个图形用户界面。我需要使用一个名为“打印”的按钮,该按钮将直接开始打印我设置的文件,而不会打开默认的打印对话框。 我需要先检查我的计算机是否连接了打印机?
我正在使用Java的Swing创建一个图形用户界面。我需要使用一个名为“打印”的按钮,该按钮将直接开始打印我设置的文件,而不会打开默认的打印对话框。 我需要先检查我的计算机是否连接了打印机?
可能会使用PrintServiceLookup吗?
该类的实现提供了特定类型打印服务(通常相当于打印机)的查找服务。
DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet();
aset.add(MediaSizeName.ISO_A4);
PrintService[] pservices =PrintServiceLookup.lookupPrintServices(flavor, aset);
if (pservices.length > 0) {
DocPrintJob pj = pservices[0].createPrintJob();
//....
}
import java.awt.print.*;
import javax.print.*;
import javax.print.attribute.*;
import java.text.*;
import javax.print.attribute.standard.*;
public class ShowPrinters {
public ShowPrinters() {
}
public static void main(String[] args) {
DocFlavor myFormat = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PrintService[] services =PrintServiceLookup.lookupPrintServices(myFormat, aset);
System.out.println("The following printers are available");
for (int i=0;i<services.length;i++) {
System.out.println(" service name: "+services[i].getName());
}
}
}
AttributeSet attributes = new HashPrintServiceAttributeSet(
new PrinterName(printerName, Locale.getDefault()));
PrintService[] services = PrintServiceLookup.lookupPrintServices(
DocFlavor.SERVICE_FORMATTED.PRINTABLE,
attributes);
PrintService printService = services[0];
PrintServiceAttributeSet printServiceAttributes = printService.getAttributes();
PrinterState printerState = (PrinterState) printServiceAttributes.get(PrinterState.class);