basic java gui program

405 Views Asked by At

I need help writing a GUI application that:

• When an attempt is made to close the window, the user should be asked via a dialog to confirm that they indeed wish to terminate the application, via supplying a y (yes) or n (no) indication. If ‘y’ is entered then the application should immediately terminate, if ‘n’ is entered it should stay visible. i almost have this down, but I cant get the window to stay visible after clicking no on the JOptionPane.showConfirmDialog();

• When the user minimises the window by clicking the appropriate icon, a message dialog should appear saying “Minimising the window”

• When the user restores the window, a message dialog should appear saying “Restoring the window”. This would be of great help to me.

1

There are 1 best solutions below

0
On

For the first part of the question: You can add a WindowListener to your application's top level JFrame containing the following:

addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
        doExit(); // Will not return if user clicks yes.
        super.windowClosing(e);
    }
});

... and then implement doExit() as follows:

private void doExit() {
    int yesNo = JOptionPane.showConfirmDialog(this, "Are you sure you wish to exit?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

    if (yesNo == JOptionPane.YES_OPTION) {
        System.exit(0);
    }
}

In addition you need to add the following method call when initialising your application:

mainAppFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);