简体   繁体   中英

Java's swing print() usage

Does java's swing print() have to be called on the EDT (event dispatch thread)?

It is taking an extended amount of time to execute and long running things being on the EDT are a pain, as we all know.

Short answer, no, the printing does not need to take place on the EDT.

This is covered in the official tutorial: How to Print Text

Printing Interactively or Non-interactively

In interactive mode a progress dialog with an abort option is shown for the duration of printing. Here is a sample of a progress dialog.

This dialog allows the user to keep track of printing progress. The progress dialog is modal when the print method is called on the event dispatch thread and non-modal otherwise. It is important that your document remain unchanged while being printed, otherwise the printing behavior is undefined. The print method ensures that your document will not be changed and disables the component for the duration of printing.

If you call the print method on the event dispatch thread in non-interactive mode, then all events including repaints will be blocked. That is why printing non-interactively on EDT is only recommended for applications with non-visible GUI.

Be aware though, JTextComponent is the only Swing component that can be printed on a background thread, by using its dedicated print methods. The print method inherited from JComponent is not thread safe.

In general: Swing is single threaded except when stated otherwise. JTextComponent's dedicated print method explicitly states it is thread safe:

http://docs.oracle.com/javase/7/docs/api/javax/swing/text/JTextComponent.html#print(java.text.MessageFormat,%20java.text.MessageFormat,%20boolean,%20javax.print.PrintService,%20javax.print.attribute.PrintRequestAttributeSet,%20boolean)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM