Rene
Rene

Reputation: 69

Java: JOptionPane affects parent JFrame? (includes SSCCE)

Given the following applet:

import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.lang.reflect.InvocationTargetException;

import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Example extends JApplet
{
   JPanel aPanel;

   @Override
   public void init()
   {
      try
      {
         javax.swing.SwingUtilities.invokeAndWait(new Runnable()
         {
            public void run()
            {
               makeGui();
            }
         });
      }
      catch (InterruptedException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      catch (InvocationTargetException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }      
   }

   public void makeGui()
   {
      aPanel = new JPanel(new BorderLayout());

      this.getContentPane().add(aPanel, BorderLayout.CENTER);

      JFrame aTestFrame =new JFrame();
      aTestFrame.setBounds(new Rectangle(200,200));
      JPanel aTestPanel = new JPanel(new BorderLayout());
      aTestPanel.setBounds(new Rectangle(200,200));

      aTestFrame.add(aTestPanel);
      aTestFrame.setVisible(true);
      JOptionPane.showMessageDialog(aTestFrame, "arfarf");


   }

}

Why does the JOptionPane call closes aTestFrame? If i leave out the call the 2 frames render correctly, but when i click on OK in the JOptionPane the parent JFrame is closed.

The first answer is correct, apparently there is a focus issue.. THANKS!

Upvotes: 4

Views: 620

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

I think that you're better off not using a JFrame with a JApplet, but instead using a JDialog that is tied into the JApplet's Window ancestor:

   public void makeGui() {
      aPanel = new JPanel(new BorderLayout());

      this.getContentPane().add(aPanel, BorderLayout.CENTER);

      Window win = SwingUtilities.getWindowAncestor(Example.this);

      JDialog dialog = new JDialog(win, "My Dialog", ModalityType.MODELESS);

      JPanel dialogPanel = new JPanel();
      dialogPanel.setPreferredSize(new Dimension(200, 200));
      dialog.add(dialogPanel);
      dialog.pack();
      dialog.setVisible(true);

      JOptionPane.showMessageDialog(dialog, "arfarf");
   }

Upvotes: 2

Related Questions