我们正在使用新的 Java 打印 API,它使用 PrinterJob.printDialog(attributes)
向用户显示对话框。
为了下次保存用户的设置,我想这样做:
PrintRequestAttributeSet attributes = loadAttributesFromPreferences();
if (printJob.printDialog(attributes)) {
// print, and then...
saveAttributesToPreferences(attributes);
}
但是,我通过这样做发现有时(我还没有弄清楚如何)属性会在内部获取一些错误数据,然后当您打印时,您会得到一个空白的白页。然后代码将中毒设置保存到首选项中,所有后续打印运行也会得到中毒设置。此外,练习的整个要点,使新运行的设置与用户为上一次运行选择的设置相同,都失败了,因为新对话框似乎没有使用旧设置。
所以我想知道是否有正确的方法来做到这一点。 Sun 肯定不打算让用户在每次应用程序启动时都必须选择打印机、页面大小、方向和页边距设置。
编辑以显示存储方法的实现:
private PrintRequestAttributeSet loadAttributesFromPreferences()
{
PrintRequestAttributeSet attributes = null;
byte[] marshaledAttributes = preferences.getByteArray(PRINT_REQUEST_ATTRIBUTES_KEY, null);
if (marshaledAttributes != null)
{
try
{
@SuppressWarnings({"IOResourceOpenedButNotSafelyClosed"})
ObjectInput objectInput = new ObjectInputStream(new ByteArrayInputStream(marshaledAttributes));
attributes = (PrintRequestAttributeSet) objectInput.readObject();
}
catch (IOException e)
{
// Can occur due to invalid object data e.g. InvalidClassException, StreamCorruptedException
Logger.getLogger(getClass()).warn("Error trying to read print attributes from preferences", e);
}
catch (ClassNotFoundException e)
{
Logger.getLogger(getClass()).warn("Class not found trying to read print attributes from preferences", e);
}
}
if (attributes == null)
{
attributes = new HashPrintRequestAttributeSet();
}
return attributes;
}
private void saveAttributesToPreferences(PrintRequestAttributeSet attributes)
{
ByteArrayOutputStream storage = new ByteArrayOutputStream();
try
{
ObjectOutput objectOutput = new ObjectOutputStream(storage);
try
{
objectOutput.writeObject(attributes);
}
finally
{
objectOutput.close(); // side-effect of flushing the underlying stream
}
}
catch (IOException e)
{
throw new IllegalStateException("I/O error writing to a stream going to a byte array", e);
}
preferences.putByteArray(PRINT_REQUEST_ATTRIBUTES_KEY, storage.toByteArray());
}
编辑: 好吧,它不记得打印机的原因似乎是它根本不在 PrintRequestAttributeSet 中。事实上,页边距和页面大小会被记住,至少在设置随机中毒之前是这样。但是用户选择的打印机不在这里:
[0] = {java.util.HashMap$Entry@9494} class javax.print.attribute.standard.Media -> na-letter
[1] = {java.util.HashMap$Entry@9501} class javax.print.attribute.standard.Copies -> 1
[2] = {java.util.HashMap$Entry@9510} class javax.print.attribute.standard.MediaPrintableArea -> (10.0,10.0)->(195.9,259.4)mm
[3] = {java.util.HashMap$Entry@9519} class javax.print.attribute.standard.OrientationRequested -> portrait
最佳答案
看来您正在寻找的是 PrintServiceAttributeSet ,而不是 PrintRequestAttributeSet
。
看看 PrintServiceAttribute接口(interface),并查看您需要的元素是否已作为类实现。如果没有,您可以实现自己的 PrintServiceAttribute
类。
关于java - 有没有一种好方法可以在 Swing 应用程序中保留打印机设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4263866/