java 单击按钮后打开一个新的 JFrame 并关闭上一个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28860914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:18:10  来源:igfitidea点击:

Opening a new JFrame and close previous after clicking button

javaswingjframejbutton

提问by Steven

How can I code a button that, when clicked, closes the current JFrameand opens a new one?

我如何编写一个按钮,点击时关闭当前按钮JFrame并打开一个新按钮?

This is what I have so far, but the old frame stays open:

到目前为止,这是我所拥有的,但旧框架保持打开状态:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    practise1 s = new practise1();
    s.setVisible(true);
} 

I have tried using .close()after the first {but it gives me an error.

我试过.close()在第一个之后使用,{但它给了我一个错误。

回答by sneelhorses

If you plan on using the originial JFrame later, use setVisible(false)on the original JFrame. If you plan on closing the first JFrame and never reusing it, you can use dispose().

如果您打算稍后使用setVisible(false)原始 JFrame,请在原始 JFrame 上使用。如果您打算关闭第一个 JFrame 并且不再重用它,您可以使用dispose().

回答by Raildex

  public void actionPerformed(ActionEvent e)
  {
    if(e.getSource () == button)
    {
      test = new JFrame();
      test.setSize(300,300);
      test.setVisible (true);
      this.dispose();

    }
  }

Dispose AFTER creating the new Frame.

创建新框架后处置。

回答by Steven

Thanks for the help everyone. I got it working using the this.dispose(); method

谢谢大家的帮助。我使用 this.dispose(); 让它工作了。方法

回答by Parth Pithadia

Lets say current Frame is FirstFrame and clicking on JButton goes to NewFrame

假设当前 Frame 是 FirstFrame 并单击 JButton 转到 NewFrame

import javax.swing.*;

public class FirstFrame extends Jframe implements ActionListener{


  JButton button;    

  public FirstFrame(){
   setVisible(true);
   setSize(500,500);

    button=new JButton("Click me");
    button.addActionListner(this);
   add(button);     
  }

  public static void main(String[] args)
  {
   new FirstFrame();
  }

  public void actionPerformed(ActionEvent e)
   {
   if(e.getSource()==button)
    {
        NewFrame nf=new NewFrame();    // Clicking on the Button will OPEN new Frame in NewFrame.java file 
        dispose();  //this method will close the FirstFrame 
     }
   }


}