⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 gamecanvasexample.java

📁 《J2ME Game Programming》随书光盘源代码
💻 JAVA
字号:
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import java.io.IOException;

/**
 * A very basic midlet to run our GameCanvas example.
 */

public class GameCanvasExample extends MIDlet
{
   private MyGameCanvas myCanvas;

   public GameCanvasExample()
   {
      myCanvas = new MyGameCanvas();
   }

   protected void startApp() throws MIDletStateChangeException
   {
      Display.getDisplay(this).setCurrent(myCanvas);
      myCanvas.start();
   }

   protected void pauseApp()
   {
   }

   protected void destroyApp(boolean unconditional) throws MIDletStateChangeException
   {
   }
}


/**
 * A class which extends the new MIDP 2 Game Canvas.
 */

class MyGameCanvas extends GameCanvas implements Runnable
{
   private boolean running;
   private int x, y;
   private Image alienHeadImage = null;

   public MyGameCanvas()
   {
      super(true);

      x = getWidth() / 2;
      y = getHeight() / 2;

      try
      {
         alienHeadImage = Image.createImage("/alienhead.png");
      }

      catch (IOException ioe)
      {
         System.out.println("unable to load image");
      }
   }

   public void start()
   {
      running = true;
      Thread t = new Thread(this);
      t.start();
   }

   public void run()
   {
      Graphics g = getGraphics();

      while (running)
      {
         // handle the state of keys
         int keyStates = getKeyStates();

         if ((keyStates & LEFT_PRESSED) != 0)   x--;
         if ((keyStates & RIGHT_PRESSED) != 0)  x++;
         if ((keyStates & UP_PRESSED) != 0)     y--;
         if ((keyStates & DOWN_PRESSED) != 0)   y++;

         if (x < 0) x = getWidth();
         if (x > getWidth()) x = 0;
         if (y < 0) y = getHeight();
         if (y > getHeight()) y = 0;

         // draw the world
         g.setColor(0x000000);
         g.fillRect(0, 0, getWidth(), getHeight());
         g.drawImage(alienHeadImage, x, y, Graphics.VCENTER|Graphics.HCENTER);

         // flush the graphics buffer (GameCanvas will take care of painting)
         flushGraphics();

         // sleep a little
         try
         {
            Thread.sleep(10);
         }
         catch (InterruptedException ie)
         {
         }
      }
   }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -