桌球案例
图片资源:
代码
java">package com.bjsxt;
import java.awt.*;
import javax.swing.*;import static com.sun.glass.ui.Cursor.setVisible;public class BallGame extends JFrame {Image ball = Toolkit.getDefaultToolkit().getImage("../../images/ball.png");Image desk = Toolkit.getDefaultToolkit().getImage("../../images/desk.jpg");double x = 200;double y = 200;double degree = 3.14 / 3; // 弧度 3.14 = 180° 60°// 绘制窗口public void paint(Graphics g) {System.out.println("窗口被画一次");g.drawImage(desk, (int)0, (int)0, null);g.drawImage(ball, (int)x, (int)y, null);x = x + 10*Math.cos(degree);y = y + 10*Math.sin(degree);if (y > 501 - 40 - 50 || y < 40){degree = - degree;}// 碰到左右边界if(x > 856 - 40 - 50 || x < 40){degree = 3.14 - degree;}}void launchFrame(){setSize(856, 501);setLocation(100, 100);setVisible(true);while(true){repaint();try{Thread.sleep(40); // 1s = 1000ms; 大约1秒绘制1000/40=25次} catch(InterruptedException e){e.printStackTrace();}}}public static void main(String[] args) {System.out.println("我的小游戏开始啦");BallGame game = new BallGame();game.launchFrame();}
}