代碼如下
<font size="3">package Game;import java.awt.Graphics;import java.awt.Image;import javax.swing.JPanel;public class BackgroundPanel extends JPanel { PRivate static final long serialVersionUID = 1L; private Image image;// 背景圖片 public BackgroundPanel() { setOpaque(false); setLayout(null); } public void setImage(Image image) { this.image = image; } /** * 畫出背景 */ protected void paintComponent(Graphics g) { if (image != null) { // 圖片寬度 int width = getWidth(); // 圖片高度 int height = getHeight(); // 畫出圖片 g.drawImage(image, 0, 0, width, height, this); } super.paintComponent(g); }}</font>
<font size="3">package Game;import java.awt.Container;import java.awt.event.*;import javax.swing.*;public class BirdLabel extends JLabel implements Runnable { private static final long serialVersionUID = 1L; // 隨機(jī)生成線程的休眠時(shí)間,即控制小鳥移動(dòng)速度 private int sleepTime = (int) (Math.random() * 300) + 5; private int y = 100; private Thread thread;// 將線程作為成員變量 private Container parent; private int score = 15;// 該類角色對(duì)應(yīng)的分?jǐn)?shù) /** * 構(gòu)造方法 */ public BirdLabel() { super(); // 創(chuàng)建小鳥圖標(biāo)對(duì)象 ImageIcon icon = new ImageIcon(getClass().getResource("bird.gif")); setIcon(icon);// 設(shè)置控件圖標(biāo) addMouseListener(new MouseAction());// 添加鼠標(biāo)事件監(jiān)聽器 // 添加控件事件監(jiān)聽器 addComponentListener(new ComponentAction()); thread = new Thread(this);// 創(chuàng)建線程對(duì)象 } /** * 控件的控件事件監(jiān)聽器 */ private final class ComponentAction extends ComponentAdapter { public void componentResized(final ComponentEvent e) { thread.start();// 線程啟動(dòng) } } /** * 控件的鼠標(biāo)事件監(jiān)聽器 */ private final class MouseAction extends MouseAdapter { public void mousePressed(final MouseEvent e) { if (!MainFrame.readyAmmo())// 如果子彈沒(méi)有準(zhǔn)備好 return;// 什么也不做 MainFrame.useAmmo();// 消耗子彈 appScore();// 加分 destory();// 銷毀本組件 } } public void run() { parent = null; int width = 0; try { while (width <= 0 || parent == null) { if (parent == null) { parent = getParent();// 獲取父容器 } else { width = parent.getWidth();// 獲取父容器的寬度 } Thread.sleep(10); } for (int i = width; i > 0 && parent != null; i -= 8) { setLocation(i, y);// 從右向左移動(dòng)本組件位置 Thread.sleep(sleepTime);// 休眠片刻 } } catch (InterruptedException e) { e.printStackTrace(); } if (parent != null) { MainFrame.appScore(-score * 10); // 自然銷毀將扣分 } destory();// 移動(dòng)完畢,銷毀本組件 } /** * 從容器移除本組件的方法 */ public void destory() { if (parent == null) return; parent.remove(this);// 從父容器中移除本逐漸 parent.repaint(); parent = null; // 通過(guò)該語(yǔ)句終止線程循環(huán) } /** * 加分的方法 */ private void appScore() { System.out.println("小鳥被擊中"); MainFrame.appScore(15); }}</font>
詳細(xì)說(shuō)明:http://java.662p.com/thread-3575-1-1.html
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注