Search code examples
javamultithreadingswingjoptionpanejcomponent

is it possible to have multiple JOptionPane dialogs?


does anyone know how do we have a JOptionPane dialog above another JOptionPane dialog?


Solution

  • I would use JDialogs for this as I think that this gives you a bit more control over how code gets run and displayed. But it could be done with JOptionPanes as well. For instance if you displayed a JButton in the JOptionPane whose ActionListener caused the display of another JOptionPane.

    For e.g.,

    import java.awt.event.ActionEvent;
    import javax.swing.AbstractAction;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    
    public class NestedJOptions {
       public static void main(String[] args) {
          final JPanel panel = new JPanel();
          panel.add(new JButton(new AbstractAction("Push Me") {
             public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(panel, "hello world!");
             }
          }));
    
          JOptionPane.showMessageDialog(null, panel);
       }
    }