【发布时间】: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,非常笨重且过时。