如何在不退出应用程序的情况下根据JPanel上的事件关闭特定的JFrame?

时间:2013-07-24 08:42:41

标签: java swing jframe jpanel multiple-instances

如何在不退出整个应用程序的情况下,根据特定帧内JPanel上的模拟退出特定帧?

在我的主要课程中,我有一个Frame()方法

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

在我的FightScene课程中,我正在绘制一个fightscene,该类也有checkCollision()方法

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

2 个答案:

答案 0 :(得分:9)

JFrame#setDefaultCloseOperation设为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);

现在关闭框架只需:

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

<强>更新

  

我理解但是如何使用FightScene()触发这个(这是   一个JPanel)?

通过构造函数 setter JFrame的实例传递给JPanel

如果您不想在JPanel类/方法中使用实例,请执行以下操作:

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

答案 1 :(得分:0)

((帧)FightScene.this.getTopLevelAncestor())处理(); // FightScene是JPanel