Reputation: 466
Recently I have been working on a project which uses Java Swing to build the GUI. I want to print the text in a JTextArea
and therefore I wrote something like
boolean printed = textArea.print();
This brings up a modal dialog. However the dialog seems to have no parent and the main frame (the one containing textArea
) blocks the print dialog.
As you see, the print dialog (the thin line at the bottom) goes behind the main JFrame
.
Code:
import java.awt.*;
import java.awt.print.*;
import javax.swing.*;
public class JTextAreaPrintBug {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,600);
frame.setLocationRelativeTo(null);
frame.setAlwaysOnTop(true);
//now add JTextArea
frame.setLayout(new BorderLayout());
JTextArea textArea = new JTextArea();
frame.add(textArea, BorderLayout.CENTER);
frame.setVisible(true);
try {
textArea.print();
} catch (PrinterException ex) {}
}
});
}
}
Is it possible to bring the print dialog to front (or explicitly set the parent of the print dialog), preferably not reinventing the wheel? Thanks in advance.
Edit: I know there is a line frame.setAlwaysOnTop(true);
. What I really want is to bring the print dialog to the very front even if the main frame is always on top.
Edit (2): I finally opted for a workaround which uses a WindowFocusListener
and the getOppositeWindow()
method in WindowEvent
to obtain a reference to the print dialog. Still I resort to reflection (getting the name of the instance's class) to check whether the "opposite window" is a print dialog, or just an ordinary dialog in my application. Anyway, welcome for more elegant solutions.
Upvotes: 1
Views: 756
Reputation: 3669
It's because of this
frame.setAlwaysOnTop(true);
So change it to false
to see the print window.
or
Remove that line, if you don't want your main window to block other windows. Default value is false anyway.
Upvotes: 2