【问题标题】:Close a container on button click单击按钮关闭容器
【发布时间】:2017-04-11 04:40:52
【问题描述】:

我试图从另一个类 ABC 中显示一个名为 testView 的类的窗口。窗口包含一个按钮。我想在单击该按钮时关闭窗口。我怎样才能关闭它?

public class testView extends JFrame {

  protected JButton closeButton = new JButton("Close");

  testView(){

    this.setSize(1000,700);
    this.setTitle("Test");
    Container window = getContentPane();
    window.setLayout(new FlowLayout());
    this.setResizable(false);

    window.add(closeButton);
  }
}

public class ABC{
  public static void main(String[] args) {

     testView View = new testView(); 

     View.setVisible(true); 
  }
}

从另一个类 ABC 显示窗口。如何在按钮单击时关闭窗口?

【问题讨论】:

  • 只需使用 Dispose() 方法关闭它

标签: java swing window jbutton


【解决方案1】:

你可以这样做:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
       frameToClose.dispose();
    }
});

此代码添加了一个按钮动作侦听器,然后它告诉框架在该按钮具有对其执行的动作时关闭。希望这会有所帮助:)

【讨论】:

    【解决方案2】:

    要使窗口不可见,您必须调用

    java.awt.Window.setVisible(false)
    

    但是使用dispose 方法,您可以从内存中删除您的窗口。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 2012-04-24
      相关资源
      最近更新 更多