Question

Why this code do not stop when the while loop is empty. If I add an instruction the code work fine. Normally after the the user clicked an button the test variable will be changed so the loop will ends. Is there another way to test that the JDialog was disposed.

public class FenetreAjoutClass extends JDialog {
    private JPanel pan = new JPanel();
    private JPanel buttPan = new JPanel();
    private JTextField schoolLevl = new JTextField();
    private JButton valide = new JButton("OK");
    private static String infos = null;
    private static boolean test = false;

    private JButton cancel = new JButton("CANCEL");

    FenetreAjoutClass(JFrame parent, Boolean modal) {
        valide.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                infos = schoolLevl.getText();
                test = true;
                dispose();

            }
        });

        cancel.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                test = true;
                dispose();

            }
        });
        this.setLocationRelativeTo(null);
        this.setResizable(true);
        this.setLayout(new BorderLayout());
        pan.setLayout(new GridLayout(1, 1));
        pan.add(schoolLevl);
        this.add(pan, BorderLayout.NORTH);
        buttPan.add(valide);
        buttPan.add(cancel);
        this.add(buttPan, BorderLayout.SOUTH);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        System.out.println(get());
    }

    public static String get() {
        new FenetreAjoutClass(null, false);
        while (!test) {
            //System.out.println(test);
        }
        return infos;
    }
}
Was it helpful?

Solution

The dispose will free up your memory. All data for the dialog are gone. If you want to show the window later again you have to work with visibility. This can be checked with isVisible().

You can replace the dispose() in your code with this.setVisible(false)

public static String get() {
        FenetreAjoutClass dialog = new FenetreAjoutClass(null, false);
        while (dialog.isVisible()) {
            System.out.println("is Visible");
        }
        System.out.println("is not Visible");
        return infos;
}

Mind that the console will still print "is Visible" over a short time after the dialog is closed. But this is because the console can does not print as quick as the while loop restarts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top