Reputation:
I have a JFrame that launches a dialog on a button click. I would like a different button to launch 2+ dialogs that are modal to the parent frame (to allow side by side comparison and interaction of the 2 dialogs but not allow the user to interact with the parent frame). Is it possible to do this using dialogs or should I resort to frames?
Upvotes: 1
Views: 1437
Reputation:
I found what I was looking for. Basically I set the dialog modal to false and on launch I set the parent frame to be disabled. Then I keep count of the number of dialogs open and when all of them are closed, I re-enable it.
Upvotes: 0
Reputation: 285403
Again, you could make one JDialog modal, and set its parent window to the main JFrame, and make the 2nd dialog modeless, and set its parent window to the first dialog. Something like:
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MultipleDialogs {
@SuppressWarnings("serial")
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
final JFrame mainFrame = new JFrame("Main JFrame");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setPreferredSize(new Dimension(400, 300));
JPanel panel = new JPanel();
panel.add(new JButton(new AbstractAction("Two Dialogs") {
@Override
public void actionPerformed(ActionEvent e) {
JDialog dialog1 = new JDialog(mainFrame, "Dialog 1 -- modal", ModalityType.APPLICATION_MODAL);
dialog1.setPreferredSize(new Dimension(200, 100));
dialog1.pack();
dialog1.setLocationByPlatform(true);
JDialog dialog2 = new JDialog(dialog1, "Dialog 2 -- nonmodal", ModalityType.MODELESS);
dialog2.setPreferredSize(new Dimension(200, 100));
dialog2.pack();
dialog2.setLocationByPlatform(true);
dialog2.setVisible(true);
dialog1.setVisible(true);
}
}));
mainFrame.add(panel);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
});
}
}
Make sure that you set the modal dialog visible after displaying the first dialog.
Upvotes: 2