Link to home
Start Free TrialLog in
Avatar of meow00
meow00

asked on

How do I close a JFrame ???

Hi Experts,

   In the end following code, every time when the gameOver() is called, it creates a new Test(). Therefore, after several runs ... I got many Test() and many JFrame .... How do I close the previous one after a new one is created ??? many thanks !!!


public class Test extends JFrame implements KeyListener, ActionListener{
           
         // --- blah blah ....
 
          public Test() {

         // --- blah blah ....                      
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(425,425) ;
        show() ;
       
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Test mySnake = new Test() ;
       
    }
   
    public void actionPerformed(ActionEvent e) {
               blah .....    
         if(e.getSource() == restart){ Test PlayAgain = new Test() ;}
               blah .....
   }

      public void gameOver(){
           //   blah ....  
        restart = new JButton() ;
        restart.setText("Play Again!") ;
        restart.setSize(150,30) ;
        restart.setLocation(125,150) ;
        restart.addActionListener(this) ;
        getContentPane().add(restart) ;
          // blah ...
       }
}

Avatar of Mick Barry
Mick Barry
Flag of Australia image

you need to keep a reference to the current frame and call its dispose() method to close it.
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial