Java:JOptionPane会影响父JFrame吗? (包括SSCCE)

给出以下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");


   }

}

为什么JOptionPane调用会关闭aTestFrame?如果我省略了呼叫2帧正确渲染,但是当我在JOptionPane中单击OK时,父JFrame将关闭.

第一个答案是正确的,显然有一个焦点问题..谢谢!

解决方法:

我认为最好不要将JFrame与JApplet一起使用,而是使用与JApplet的Window祖先绑定的JDialog:

   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");
   }
上一篇:使用Java发出DNS请求并对响应进行计时


下一篇:java – 同一个jvm中两个应用程序的静态变量冲突