【问题标题】:Why does my AWT Java Window not close, when I push X to the close window?当我将 X 推到关闭窗口时,为什么我的 AWT Java 窗口没有关闭?
【发布时间】:2020-05-12 21:34:25
【问题描述】:

您好,我为 AWT Window 创建了这个 java 代码

package labelExample;
import java.awt.*;  
import java.awt.event.*;  
public class labelExample extends Frame implements ActionListener{  
    Frame f;
    TextField tf; Label l; Button b;  
    labelExample(){
        Frame f=new Frame("Label Example");
        tf=new TextField("www.google.de");  
        tf.setBounds(50,50, 150,20);  
        l=new Label();  
        l.setBounds(50,100, 250,20);      
        b=new Button("Find IP");  
        b.setBounds(50,150,60,30);  
        b.addActionListener(this);    
        add(b);add(tf);add(l);    
        setSize(400,400);  
        setLayout(null);  
        setVisible(true);
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                f.dispose(); // use dispose method 
             }
         }
         );
    }            
    public void actionPerformed(ActionEvent e) {  
        try{  
        String host=tf.getText();  
        String ip=java.net.InetAddress.getByName(host).getHostAddress();  
        l.setText("IP of "+host+" is: "+ip);  
        }catch(Exception ex){System.out.println(ex);}  
    }  
    public static void main(String[] args) {  
        new labelExample();  
    }  
    }

当我尝试按 X 按钮关闭窗口时,什么也没有发生。窗户 保持打开状态。我对示例代码进行了这些更改: 公共类 labelExample 扩展 Frame 实现 ActionListener{
我添加了名为“标签示例”的新 awt-frame f。
帧 f; frame f=new Frame("标签示例"); 并添加此代码以关闭框架

f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
         f.dispose(); // use dispose method 
         }
         }
         );

如何更改我的代码来解决这个问题?

【问题讨论】:

  • 您在这里处理两个不同的Frame 实例,一个是new Frame("Label Example"),另一个是labelExample 的实例。
  • 使用windowClosed而不是windowClosing(可能会否决关闭/保存)
  • 我改成了windowClosed。我的问题是一样的。
  • 去掉你的f框架,用addWindowListener替换f.addWindowListener,用f.dispose()替换f.dispose()
  • 您为什么要使用 AWT?它是最古老的 Java GUI,非常笨重且过时。

标签: java awt


【解决方案1】:

我认为在labelExample(){ ... } 中应该添加一行setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 来关闭窗口。

【讨论】:

  • 那是 Swing,不是 AWT。
  • 此选项仅适用于swing call。
猜你喜欢
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 2016-10-15
  • 1970-01-01
  • 2021-04-08
  • 1970-01-01
  • 2012-12-15
相关资源
最近更新 更多