JDialog allows main application to lose focus
I wonder why my JDialog is pushing my main application in the background. This means that if the JDialog is displayed and the user clicks OK or CANCEL, the main application will lose focus and will be pushed into the background.
After my investigation, it turned out that this behavior only happens if I disable my main frame while I show the JDialog.
This behavior can be reproduced with the following code:
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class FocusTest {
private JFrame frame;
public FocusTest() {
frame = new JFrame();
frame.setSize(200,200);
JButton btn = new JButton("Open Dialog");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
callDialog(null, "title", "message");
}
});
frame.add(btn);
frame.setVisible(true);
}
private void callDialog(Component parent, String title, String message) {
frame.setEnabled(false);
Thread t1 = new Thread(new Runnable() {
public void run() {
JOptionPane optionPane = new JOptionPane("",
JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
JDialog dialog = optionPane.createDialog(null, "");
dialog.setVisible(true);
frame.setEnabled(true);
}
});
t1.start();
}
public static void main(String[] args) {
new FocusTest();
}
}
code>
How can I avoid the main application losing focus? (without including the main frame)
source to share
It sounds like you want a simple model dialog (i.e. a dialog that pops up and prevents the user from doing anything else before it is closed). Java makes this very easy - just use the static methods of JOptionPane to create the dialog you want.
Try replacing the body of the callDialog function like this:
int result = JOptionPane.showConfirmDialog(frame, message, title,
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
A Yes / No dialog box appears, preventing you from doing anything with the frame until the user clicks Yes or No.
If that doesn't suit your needs, try calling frame.toFront()
and it will bring it JFrame
back to the foreground.
source to share