简体   繁体   English

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

[英]Opening a new JFrame and close previous after clicking button

How can I code a button that, when clicked, closes the current JFrame and opens a new one?如何编写一个按钮,单击该按钮时关闭当前JFrame并打开一个新的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() ,但它给了我一个错误。

If you plan on using the originial JFrame later, use setVisible(false) on the original JFrame.如果您打算稍后使用原始 JFrame,请在原始 JFrame 上使用setVisible(false) If you plan on closing the first JFrame and never reusing it, you can use dispose() .如果您打算关闭第一个 JFrame 并且不再重用它,则可以使用dispose()

  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.创建新框架后处置。

Thanks for the help everyone.谢谢大家的帮助。 I got it working using the this.dispose();我使用 this.dispose(); 让它工作了。 method方法

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 
     }
   }


}

you just put this in your code :你只是把它放在你的代码中:

(the exemple here i JButton to do this with the ActionPerformed method) (这里的示例是 JButton 使用 ActionPerformed 方法执行此操作)

/**********************************************************************/ /***************************************************** ************************/

private void openBTNActionPerformed(java.awt.event.ActionEvent evt) {                                                  
        dispose();
        FrameTarget t = new FrameTaregt();
        t.setVisible(true);
        //set the size : 1250 pixels de width and 720 pixels de height
        t.setSize(1250, 720);
        //make the frame in the center wuth this 
        t.setLocationRelativeTo(null);
        t.setResizable(true);     

}

                                             

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM