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

Java 单击按钮后打开新JFrame并关闭上一个JFrame,java,swing,jframe,jbutton,Java,Swing,Jframe,Jbutton,我如何编写一个按钮,当单击该按钮时,关闭当前的JFrame,并打开一个新的按钮 到目前为止,这是我所拥有的,但旧框架仍然开放: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { practise1 s = new practise1(); s.setVisible(true); } 我尝试在第一个{之后使用.close(),但它给了我一个错误。如果您计划以后使用原始JFrame,请在原

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

到目前为止,这是我所拥有的,但旧框架仍然开放:

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

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

如果您计划以后使用原始JFrame,请在原始JFrame上使用
setVisible(false)
。如果您计划关闭第一个JFrame并且从不重用它,则可以使用
dispose()


创建新帧后进行处理。

谢谢大家的帮助。我使用this.Dispose();方法使其正常工作。

假设当前帧是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 
     }
   }


}

您只需在代码中添加以下内容:

(这里的示例使用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);     

}

                                             

什么错误?更具体一点。这听起来像是@trashgod提供的链接中提到的
CardLayout
。有时候,引导OP走正确的道路比回答他们的确切问题要好。这就是其中的一次。事实上,这条建议会让他们走上一条不应该走的路,而且会让他们走得更远造成许多问题。有时,引导OP走上正确的道路比回答他们的确切问题要好。这就是其中之一。事实上,这条建议会让他们进一步走上一条他们不应该遵循的道路,并会导致许多问题。OP要求为多帧JFrames提供解决方案。当然,多帧并不是最好的解决方案n、 我相信OP不是GUI专家,所以为什么不让OP玩多个帧呢?OP迟早会注意到,多个帧太难维护。如果OP问如何射中自己的脚。你会帮忙吗?
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);     

}