How to close the window in AWT?

人走茶凉 提交于 2019-12-04 00:44:06

问题


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?


回答1:


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();
         }
     }
);



回答2:


You could do it like this:

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



回答3:


Try doing it like this:

class ExampleClass implements ActionListener, WindowListener
{

...

f.addWindowListener(this);

...

public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}

public void windowClosing(WindowEvent e) 
{
    System.exit(0);
}

}


来源:https://stackoverflow.com/questions/5281262/how-to-close-the-window-in-awt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!