分析代码: public MyFrame(){ actionPanel.setLayout(new FlowLayout()); actionPanel.add(buttonRestart,BorderLayout.CENTER); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().add(helpPanel,BorderLayout.NORTH); this.getContentPane().add(gamePanel,BorderLayout.CENTER); this.getContentPane().add(actionPanel,BorderLayout.SOUTH); this.setSize(700,700); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("对对碰"); this.setVisible(true); buttonRestart.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ if(flag) return ; flag = true; gamePanel.addKeyListener(gamePanel); gamePanel.addMouseListener(gamePanel); gamePanel.startGame(); buttonRestart.setEnabled(false); HelpPanel.score.setText(0+""); new Thread(new Runnable(){ @Override public void run() { nowTime = 0; while(true){ try { Thread.currentThread().sleep(1000); nowTime++; HelpPanel.setTime(nowTime); if(nowTime==100){ gamePanel.removeMouseListener(gamePanel); gamePanel.removeKeyListener(gamePanel); int score = Integer.parseInt(helpPanel.score.getText()); int record = Integer.parseInt(helpPanel.record.getText()); if(score>record){ JOptionPane.showMessageDialog(null, "游戏结束,你的得分是"+score+",刷新了历史记录"+record); helpPanel.updateBestScore(); }else{ JOptionPane.showMessageDialog(null, "游戏结束,你的得分是"+HelpPanel.score.getText()); } buttonRestart.setEnabled(true); flag = false; break; } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start();; } }); }
时间: 2024-02-26 14:53:04 浏览: 24
这段代码是一个 Java GUI 应用程序中的构造函数 `MyFrame()`。它创建了一个窗口,窗口中包含了一个游戏面板、一个帮助面板和一个动作面板,还有一个重新开始游戏的按钮。具体的实现步骤如下:
1. `actionPanel.setLayout(new FlowLayout());` 设置动作面板的布局方式为流式布局。
2. `actionPanel.add(buttonRestart,BorderLayout.CENTER);` 将重新开始游戏的按钮添加到动作面板上,位置居中。
3. `this.getContentPane().setLayout(new BorderLayout());` 设置窗口的布局方式为边界布局。
4. `this.getContentPane().add(helpPanel,BorderLayout.NORTH);` 将帮助面板添加到窗口的北部位置。
5. `this.getContentPane().add(gamePanel,BorderLayout.CENTER);` 将游戏面板添加到窗口的中央位置。
6. `this.getContentPane().add(actionPanel,BorderLayout.SOUTH);` 将动作面板添加到窗口的南部位置。
7. `this.setSize(700,700);` 设置窗口的大小为 700x700。
8. `this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);` 设置窗口的默认关闭操作为退出程序。
9. `this.setTitle("对对碰");` 设置窗口的标题为“对对碰”。
10. `this.setVisible(true);` 显示窗口。
11. `buttonRestart.addMouseListener(new MouseAdapter(){...});` 为重新开始游戏的按钮添加鼠标单击事件监听器。
12. 在鼠标单击事件监听器中,如果游戏正在进行中,则直接返回;否则,开始游戏,启动一个新的线程计时,当游戏时间达到 100 秒时,结束游戏,显示得分并更新历史记录。最后,重新启用重新开始游戏的按钮,并将游戏状态标志设置为未开始。