java實現 swing模仿金山打字 案例源碼,更多Java技術就去Java教程網。http://java.662p.com
代碼:
<font size="3">import Java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.Toolkit;import java.io.File;import java.io.IOException;import java.util.Random;import javax.imageio.ImageIO;public class Main { public char c; //蘋果上的字母 public int x = 60, y = 0; // 敵人出現的坐標 public final int XSPEED=5,YSPEED=2; //蘋果xy方向移動的速度 public int center; //初始中心值 public boolean turnleft = true; //是否向左移動 public boolean alive = true; //是否活著 public Random ran = new Random(); //隨機數的種子 public TypeFrame tf=null; //所屬的框架 public Image appleimg = null; //蘋果的圖片 public Image bg = Toolkit.getDefaultToolkit().getImage("bg.jpg"); //背景圖片 public Main(TypeFrame tf) { this.tf=tf; x = randomlocation(); //得到隨機合格的隨機x坐標 y=ran.nextInt(20); //得到隨機的y坐標 if(ran.nextInt(2)==0){ turnleft=true; }else { turnleft=false; } center = x; //設置初始中心值為x c=randomchar(); //得到隨機的字母值 try { appleimg = ImageIO.read(new File("apple.gif")); //蘋果的圖片 } catch (IOException e) { // TODO Auto-generated catch block e.PRintStackTrace(); } } public void draw(Graphics g) { Color color = g.getColor(); //得到上下文顏色 g.setColor(Color.red); //設置上下文顏色 g.setFont(new Font("Dialog", 4, 40)); //設置字體 if (alive) { g.drawImage(appleimg, x, y, null); //繪制蘋果圖片 g.drawString(c+ "", x + 20, y + 60); //繪制蘋果字母 } g.setColor(color); //將上下文顏色設置回去 } public int randomlocation(){ //產生蘋果的隨機橫坐標的函數 int x1=ran.nextInt(TypeFrame.GAME_WIDTH - 40); for (int i = 0; i < tf.apples.size(); i++) { if(Math.abs(x1-tf.apples.get(i).x)<60){ return randomlocation(); } } return x1; } public char randomchar(){ //產生不與存在的蘋果字母相同的字母的方法 char ch=(char)('a'+ran.nextInt(26)); for (int i = 0; i < tf.apples.size(); i++) { if(ch==tf.apples.get(i).c) return randomchar(); } return ch; }} </font>詳細說明:http://java.662p.com/thread-3680-1-1.html
新聞熱點
疑難解答