英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论