Search code examples
javaswingappletjdialogjapplet

JDialog in center of screen instead of desired center of JApplet


In my Java applet I have JDialog with couple of radioButtons.

The problem is that this applet is of dimensions 700x300 and the JDialog appears in the center of screen. I want this JDialog to appear in the center of JApplet layout. My constructor invocation looks like this:

final JDialog dialog = new JDialog(
        SwingUtilities.windowForComponent(GUIComponentContainer.getInstance().getDocumentTable()),
        I18nCommonsImpl.constants.selectCertificate(), ModalityType.APPLICATION_MODAL);

This method:

GUIComponentContainer.getInstance().getDocumentTable()

returns JTable component which is a child of my JApplet.

I also used JDialog "setLocationRelativeTo" method:

dialog.setLocationRelativeTo(GUIComponentContainer.getInstance().getApplet());

None of these seem to work. Is there any other way to accomplish my goal? I searched along SO for similar questions, but didn't see any working solutions.

Thanks in advance.


Solution

  • Getting the Window for the applet works for me, at least when the applet is launched in Eclipse. For example:

    import java.awt.Dimension;
    import java.awt.Window;
    import java.awt.Dialog.ModalityType;
    import java.awt.event.ActionEvent;
    
    import javax.swing.AbstractAction;
    import javax.swing.Box;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    @SuppressWarnings("serial")
    public class AppletCentering extends JApplet {
        @Override
        public void init() {
            final JPanel panel = new JPanel();
            panel.add(new JButton(new AbstractAction("Press Me") {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    Window win = SwingUtilities.getWindowAncestor(panel);
                    System.out.println("win class: " + win.getClass().getCanonicalName());
                    JDialog dialog = new JDialog(win, "My Dialog", ModalityType.APPLICATION_MODAL);
                    dialog.add(Box.createRigidArea(new Dimension(200, 200)));
                    dialog.pack();
                    dialog.setLocationRelativeTo(win);
                    dialog.setVisible(true);                    
                }
            }));
    
            add(panel);
        }
    }
    

    But having said this, your question begs the question: why are you even coding for an applet? These have been out of favor for years, and just recently has lost support from Oracle who has decided to finally drop applet browser plug in support.