Opening a new JFrame and close previous after clicking button

北城余情 提交于 2019-12-12 06:05:15

问题


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

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.


回答1:


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().




回答2:


  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.




回答3:


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




回答4:


Lets say current Frame is FirstFrame and clicking on JButton goes to 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 
     }
   }


}


来源:https://stackoverflow.com/questions/28860914/opening-a-new-jframe-and-close-previous-after-clicking-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!