How to close specific JFrame based on events on JPanel without exiting application?

user2556304 picture user2556304 · Jul 24, 2013 · Viewed 8.3k times · Source

How do I exit a particular frame based on a simulation on a JPanel within that particular frame without exiting entire application?

In my main class I have a Frame() method

public void FightFrame(String offensemsg){      

    JFrame frame = new JFrame("BattleView: ");
    frame.setLayout(new BorderLayout());
    FightScene sc = new FightScene();       
    frame.add(sc);
    frame.setVisible(true);
    frame.setSize(652, 480);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    sc.GenerateScene(offensemsg);
}

in my FightScene class, I am drawing out a fightscene, the class also has checkCollision() method

      public void checkCollisions() {
           for (int i = 0; i < defense.size(); i++) {
                FriendlyEntity m = (FriendlyEntity) defense.get(i);    
                Rectangle r1 = m.getBounds();    
                for (int j = 0; j<offense.size(); j++) {
                    Enemy a = (Enemy) offense.get(j);
                    Rectangle r2 = a.getBounds();    
                    if (r1.intersects(r2)) {
                        m.setHealth(-1);
                        a.setHealth(-1);
                        if(a.getHealth()==0){
                        a.setVisible(false);
                        } else if(m.getHealth()==0){
                            m.setVisible(false);
                            }                       
                }}
           }               
           if(defense.size()==0){                   
                System.out.println("You have lost the battle\n");
                //############ How can I exit the FightFrame from here?
            }else if (offense.size()==0){
                System.out.println("You have won the battle\n");
            //############# How can I exit the FightFrame from here?                    
            }
        }

Answer

David Kroukamp picture David Kroukamp · Jul 24, 2013

Set JFrame#setDefaultCloseOperation to JFrame.DISPOSE_ON_CLOSE

JFrame frame=new JFrame();//create frame

//so when we exit or dispose of Jframe it doesnt exit the entire app
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

...

frame.pack();
frame.setVisible(true);

Now to close the frame simply do:

frame.dispose();//close the `JFrame` instance

Update:

I understand but how do I trigger this withing FightScene() (which is a JPanel)?

Pass instance of JFrame to JPanel via constructor or setter

or

if you dont want to use instances in the JPanel class/method do this:

JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(this);
frame.dispose();