在Java中如何打印文本文件?

huangapple go评论69阅读模式
英文:

How do I print a text file in Java?

问题

我有一个文本编辑器,需要打印一个文本文件。我希望它显示一个打印首选项对话框,询问用户选择打印机和纸张设置,然后根据用户的请求打印文件。我希望这个对话框的图标与我的Swing应用程序的图标相同,并且最好能够匹配我的操作系统。

我查看了这个问题答案,并尝试使用java.awt.print,但当我使用它时,它只是弹出Windows记事本,并立即打印到默认打印机。我希望用户能够在打印之前选择打印机和其他选项,所以这不是一个好的方法。

然后我查看了Java打印文本教程。我编写了下面的代码:

try {
    boolean complete = TexType_Dark.textArea.print();
    if (complete) {
        System.out.println("Done!");
    }
    else {
        JOptionPane.showMessageDialog(TexType_Dark.frame, "Error while printing file.", "Error", JOptionPane.ERROR_MESSAGE);
    }
}
catch (PrinterException pe) {
    JOptionPane.showMessageDialog(TexType_Dark.frame, "Error while printing file.", "Error", JOptionPane.ERROR_MESSAGE);
}
return;

这在Nimbus L&F上完美运行,但在运行FlatLaf Dark Mac L&F时,文本几乎是白色的(就像在组件上一样)!查看使用Microsoft Print to PDF时的结果:生成的PDF的屏幕截图

我希望打印的文本始终为黑色。有没有办法做到这一点?

供参考,我正在尝试打印一个JTextArea

英文:

I have a text editor that needs to print a text file. I want it to display a print preferences dialog, asking the user to select a printer, and paper settings, then print a file on the user's request. I want this dialog's icon to be the same as my Swing application's icon, and ideally would like it to match my OS.

I looked at the answer to this question and tried to use java.awt.print but when I used it, all it did was pop up Windows Notepad, and immediately print to the default printer. I want to user to be able to select a printer and other options before printing, so this was not a good method.

I then looked at the Java print text tutorial. I came up with the code below:

try {
    boolean complete = TexType_Dark.textArea.print();
    if (complete) {
        System.out.println("Done!");
    }
    else {
        JOptionPane.showMessageDialog(TexType_Dark.frame, "Error while printing file.", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

catch(PrinterException pe) {
    JOptionPane.showMessageDialog(TexType_Dark.frame, "Error while printing file.", "Error", JOptionPane.ERROR_MESSAGE);
}
return;

This worked perfectly on the Nimbus L&F, but when running the FlatLaf Dark Mac L&F, the text was printed almost white (like it was on the component)! See result when using Microsoft Print to PDF:
Screenshot of generated PDF

I want the printed text to always be black. Is there a way to do this?

For reference, I'm trying to print a JTextArea.

答案1

得分: 0

答案是 textArea.setForeground();
感谢 @MadProgrammer 提供答案。

英文:

The answer was textArea.setForeground();.
Thanks @MadProgrammer for the answer.

huangapple
  • 本文由 发表于 2023年4月11日 08:58:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75981717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定