import javax.swing.JFrame;
public class Driver00
{
public static void main(String[] args)
{
/*Create a frame (outside box) and write what text
will be displayed as the frame title*/
JFrame frame = new JFrame("Casino Blackjack");
JFrame frame2 = new JFrame("Rules and Information");
//allows JFrame to be maximiazed on open
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame2.setExtendedState(JFrame.MAXIMIZED_BOTH);
//give frame a size
// frame.setSize(2000,2000);
//set location on the computer screen will frame appear
//frame.setLocation(200, 150);
//use this so when you press X in corner, frame will close
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add your panel to the frame. name must match Panel class name
frame.setContentPane(new PanelProject());
frame2.setContentPane(new Rules());
// always include
frame.setVisible(true);
frame2.setVisible(true);
}
}
这是启动 GUI 的应用程序,我的问题是,如果我不注释掉 frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
行,然后单击 x
按钮,它会关闭 frame
和 frame2
。反之亦然。如果我没有注释掉具有 frame
而不是 frame2
的同一行,并且单击 x
按钮,则会关闭两个框架。
我希望能够关闭框架或另一个框架,而不必担心两个框架都被关闭。
最佳答案
"I would like to be able to close on frame or the other without having to worry about both frames being closed."
首先,您需要查看 The Use of Multiple JFrames, Good/Bad Practice? 。需要强调的是,大多数选民都倾向于“坏”一方。
话虽如此,您应该考虑框架的语义。即打开另一个框架仅用于游戏说明。这看似合理,但如果你理解 modality ,您可能会同意,对于在这种情况下使用辅助框架,模式 JDialog
会更合适,因为当指令对话框打开时,主游戏框架的交互将被阻止。查看更多How to Make Dialogs
如果您不想使用两个单独的窗口,另一个选择是使用 CardLayout
。这将允许您在 View 之间交换。因此,当提示说明时,游戏将移出 View ,而说明将移入 View 。反之亦然。您可以在How to use CardLayout查看更多信息。另请参阅一个简单的示例 here
关于java - 使用 Java 关闭 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23417749/