当我按下关闭窗口时,为什么我的Java窗口没有关闭?

时间:2020-01-27 09:50:36

标签: java windows swing

我创建了此Java代码

   package javaGUI;

   import javax.swing.*;  
   import java.awt.*;  
   import java.awt.event.*;  
   public class labelSwingExample extends Frame implements ActionListener{  
JTextField tf; JLabel l; JButton b;
JFrame frame;
labelSwingExample(){
    JFrame frame = new JFrame("Test Frame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    tf=new JTextField("www.google.com");  
    tf.setBounds(50,50, 150,20);

    l=new JLabel();  
    l.setBounds(50,100, 250,20);      
    b=new JButton("Find IP");  
    b.setBounds(50,150,95,30);  
    b.addActionListener(this);    
    add(b);add(tf);add(l);    
    setSize(400,400);  
    setLayout(null);  
    setVisible(true);  
}  
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 labelSwingExample();  
} } 

现在我的问题是,当我按下关闭窗口X时,窗口没有关闭。 我在这三行代码中添加了此示例代码,以添加紧密的功能 到这个Java摆动窗口:

JFrame frame;
JFrame frame = new JFrame("Test Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

请告诉我为什么我的框架命令不起作用?

2 个答案:

答案 0 :(得分:0)

该类应扩展JFrame而不是Frame,它应类似于以下内容:

public class labelSwingExample extends JFrame implements ActionListener

答案 1 :(得分:0)

您的类扩展了Frame,您在构造函数中有一个局部变量JFrame有一个变量JFrame。(而您只是关闭最后一个)。

只需让您的类扩展JFrame,并对其本身调用setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);,就像这样:

// Minor note: I've used an uppercase `L` for your class, which is a code standard in Java
public class LabelSwingExample extends JFrame implements ActionListener{
  JTextField tf; JLabel l; JButton b;

  public LabelSwingExample(){
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ...
  }

  ...
}

不需要任何其他框架作为变量,因为您的类本身是 框架。

相关问题