gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:56:54 28 4
gpt4 key购买 nike

如何在不退出整个应用程序的情况下,基于特定框架内 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?
}
}

最佳答案

设置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

更新:

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

通过constructorsetterJFrame 的实例传递给JPanel

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

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

关于java - 如何在不退出应用程序的情况下根据 JPanel 上的事件关闭特定的 JFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17829098/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com