Java 关闭父类中的JFrame
我正要编一个小游戏。我有我的主类Java 关闭父类中的JFrame,java,swing,class,jframe,Java,Swing,Class,Jframe,我正要编一个小游戏。我有我的主类MenuFrame,从中我调用绘制游戏的Gui类 MenuFrame.java: public class MenuFrame extends JFrame implements ActionListener { private JButton start; public static void main(String[] args) { MenuFrame mainframe = new MenuFrame("Menu");
MenuFrame
,从中我调用绘制游戏的Gui
类
MenuFrame.java:
public class MenuFrame extends JFrame implements ActionListener {
private JButton start;
public static void main(String[] args) {
MenuFrame mainframe = new MenuFrame("Menu");
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setSize(600, 400);
mainframe.setLayout(null);
mainframe.setVisible(true);
}
public MenuFrame(String title) {
super(title);
start = new JButton("Start game");
start.setBounds(220, 60, 160, 40);
start.addActionListener(this);
add(start);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == start) {
game(hauptSpiel);
}
}
public static void game() {
JFrame game = new JFrame;
game.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
game.setUndecorated(true);
game.setResizable(false);
game.setSize(480, 800);
game.setLocation(1920/2-480/2, 1080/2-800/2);
game.setVisible(true);
game.add(new Gui());
}
}
如您所见,我从我的voidgame()调用我的类Gui()
在我的Gui
课上,我画了一些画
这门课看起来有点像这样:
public class Gui extends JPanel implements ActionListener {
public Gui() {
setFocusable(true);
ImageIcon i = new ImageIcon(background.jpg);
background = i.getImage();
ImageIcon b = new ImageIcon("ball.png");
ball = b.getImage();
}
public void paint(Graphics g) {
Graphics2D f2 = (Graphics2D)g;
f2.drawImage(background, 0, 0, null);
f2.drawImage(ball, 0, 600, null);
}
}
为了清晰易懂,我删除了游戏逻辑
但是,如果游戏结束,我想在MenuFrame
类中处理我的game()
JFrame
有没有什么方法可以把这件事做得干净利落 有两种方法可以让我立刻想到。我自己对这一点还相当陌生,但我自己也遇到过这种情况好几次。我是这样做的(我个人喜欢选项2,但不知道这是否是一种公认的OOP技术)
自上而下:垃圾收集
1) 在MenuFrame中有一个方法,该方法定期调用并检查GUI/游戏对象中的布尔值,该布尔值指示该对象是否完成。如果是真的,就把它处理掉
自下而上:积极主动的儿童MO
2) 在MenuFrame中有一个方法,该方法处理作为参数发送给它的对象。从“游戏”中调用所述方法,并将其自身作为参数传递。该方法可以是静态的,以解决实例问题。如果安全性是一个问题(不希望处理随机对象),则指定如果调用所述方法,则处理子“游戏”。有点像getter/setter方法,它限制了可以准确处理的内容的可能性
请也分享你的想法。空布局通常是个坏主意;不要创建新的框架,而是使用卡片布局在面板之间切换请参见,首先,感谢您的回答好的,是的,我最初想到了类似的东西。我实现了一些类似于您的第一个方法的代码,但我认为它没有那么漂亮。在阅读了CardLayout函数之后,我想我会使用CardLayout,因为它更漂亮。