0

I have got a frame in which sometimes a dialog is opened. I would like this dialog to be attached to the existing frame, so for example when I drag that frame the opened dialog follows it. I have heard that this might be possible to achieve using GlassPane but I need some hints. Right now, when I open a new dialog and set its location relative to frame it looks like this:

enter image description here

  1. I would like the "testDialog" to appear next to the frame attached to its upper-right corner.
  2. When I drag the "test" frame, the "testDialog" follows it.

Here is a working example:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Example {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                showGUI();
            }
        });
    }

    public static void showGUI() {
        final JFrame frame=new JFrame("test");
        JButton open=new JButton("Open new dialog");
        open.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("test");
                JDialog dialog=new JDialog((Frame)null,"testdialog");
                dialog.setPreferredSize(new Dimension(200,300));
                dialog.getContentPane().add(new JLabel("testlabel"));
                dialog.pack();
                dialog.setLocationRelativeTo(frame);
                dialog.setVisible(true);
            }
        });
        frame.setLayout(new FlowLayout());
        frame.getContentPane().add(open);
        frame.getContentPane().add(new JLabel("test"));
        frame.setLocationRelativeTo(null);
        frame.setPreferredSize(new Dimension(400, 200));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

}
user3111525
  • 5,013
  • 9
  • 39
  • 64

0 Answers0