Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close the window in AWT?

Tags:

java

awt

I am creating a small application using AWT. When I try to close the window, the "close" button doesn't work.

Here's my code:

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;

class ButtonDemo1 implements ActionListener {
    Button b1;
    TextField tf;
    Frame f;

    ButtonDemo1(String s) {
        f = new Frame(s);
        b1 = new Button("OK");

        tf = new TextField(10);
        f.setSize(200, 250);
        f.setVisible(true);
        b1.addActionListener(this);

        f.add(tf);
        f.add(b1);

        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        });

        f.setLayout(new FlowLayout());
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == b1) {
            tf.setText("Press Ok");
        }

    }

    public static void main(String args[]) {
        new ButtonDemo1("First");
    }
}

How can I fix the "close" button?

like image 493
Ankur jain Avatar asked Mar 12 '11 07:03

Ankur jain


People also ask

How do you close a frame?

You can close the frame programmatically by sending it the WINDOW_CLOSING event, like this: WindowEvent closingEvent = new WindowEvent(targetFrame, WindowEvent.

How do you close a Windows GUI?

By using System. exit(0); you would close the entire process.

How do I close an applet?

1 Answer. Show activity on this post. System. exit(0);

How do you stop a GUI in Java?

The first option which is the default is EXIT_ON_CLOSE which terminates the Java swing GUI program when you click the close button on the JFrame window. Another option is DISPOSE_ON_CLOSE which terminates JVM if the last displayable window is disposed of.


1 Answers

It's better to use the method public void dispose()

Why should you have to dispose() a java.awt.Window that goes out of scope?

f.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            dispose();
         }
     }
);
like image 127
satya Avatar answered Sep 19 '22 10:09

satya