Java: JOptionPane affect parent JFrame? (including 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 calling JOptionPane close aTestFrame? If I omit the call, then 2 frames display correctly, but when I click "OK" in JOptionPane, the parent JFrame closes.

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

+4
source share
1 answer

I think you better not use JFrame with JApplet, but instead use JDialog, which is bound to the predecessor of the JApplet window:

  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"); } 
+2
source

All Articles