0

I'm working in Java AWT and when the window appears, I don't know how to close it. I try to Alt+F4 or use

[setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)] but this function wasn't called in Eclipse.

Eclipse IDE version 2018-12.

 package test2;

import java.awt.Button;
import java.awt.Frame;

import javax.swing.JFrame;


public class java12 extends Frame{
public java12() {
    setTitle("Demo Java AWT");

    Button object=new Button("Click me");

    object.setBounds(100, 100, 100, 100);

    add(object);

    setSize(90, 30);

    setLayout(null);

    setVisible(true);


}

public static void main(String[] args) {
    new java12();
}

}

It only can close by Task Manager, how can I close it by put something in my code

  • Please check this question :- https://stackoverflow.com/questions/34250434/jframe-setdefaultcloseoperation-not-working, its already answered here. Extending JFrame class instead of Frame class would fix – manishgdev Jul 08 '19 at 13:46
  • Possible duplicate of [How to programmatically close a JFrame](https://stackoverflow.com/questions/1234912/how-to-programmatically-close-a-jframe) – Dorado Jul 08 '19 at 13:55
  • The question is ambiguous, did you plan to use a `Frame` or a `JFrame` ? – Arnaud Jul 08 '19 at 13:56
  • what is different between Frame and JFrame @Arnaud – Long Lê Jul 08 '19 at 15:38
  • You may want to have a look at this : https://stackoverflow.com/questions/408820/what-is-the-difference-between-swing-and-awt – Arnaud Jul 08 '19 at 16:41

1 Answers1

-1

setDefaultCloseOperation determines what happens when the close button is clicked and takes the following parameters:

  • WindowConstants.EXIT_ON_CLOSE
  • WindowConstants.DISPOSE_ON_CLOSE
  • WindowConstants.HIDE_ON_CLOSE
  • WindowConstants.DO_NOTHING_ON_CLOSE

Example :

frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
                // Ask for confirmation before terminating the program.
                int option = JOptionPane.showConfirmDialog(
                        frame, 
                        "Are you sure you want to close the application?",
                        "Close Confirmation", 
                        JOptionPane.YES_NO_OPTION, 
                        JOptionPane.QUESTION_MESSAGE);
                if (option == JOptionPane.YES_OPTION) {
                        System.exit(0);
                }
        }
});
yali
  • 1,038
  • 4
  • 15
  • 31
  • JFrame object contains `setDefaultCloseOperation` but the question is geared toward java.awt.Frame object. – Dorado Jul 08 '19 at 13:53
  • tks man, but can you put this code into my code to make it complete ?. I really don't know how to put it – Long Lê Jul 08 '19 at 15:08