3

如何在不退出整个应用程序的情况下基于该特定框架内的 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 类中,我正在绘制一个战斗场景,该类也有 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?                    
            }
        }
4

2 回答 2

9

设置JFrame#setDefaultCloseOperationJFrame.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

更新:

我明白,但我如何触发这个 withing FightScene()(这是一个 JPanel)?

通过构造函数设置器JFrame传递to的实例JPanel

或者

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

JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(this);
frame.dispose();
于 2013-07-24T08:44:35.643 回答
0

((Frame)FightScene.this.getTopLevelAncestor()).dispose(); // FightScene 是 JPanel

于 2015-10-29T01:42:34.460 回答