import java.awt.*;
import javax.swing.*;
public class BallGame extends JFrame{
Image ball = Toolkit.getDefaultToolkit().getImage("images/ball.png");
Image desk = Toolkit.getDefaultToolkit().getImage("images/table.jpg");
// double degree = 3.14/3;
double x = 100;//小球的横坐标
double y = 100;//小球的纵坐标
boolean right=true;
public void paint(Graphics g) {
g.drawImage(desk, 0, 0, null);//注意顺序,先画桌子再画小球
g.drawImage(ball, (int)x, (int)y, null);//强制类型转化,将double型的x和y都转为int型
// x = x + 10 * Math.cos(degree);
// y = y + 10 * Math.sin(degree);
// x+=5;
if(x>(856-40-30)) {
right=false;
}
if(x<40) {
right=true;
}
if(right){
x+=5;
}
else x-=5;
// y=y+10;
//碰到上下边界
// if(y > 500 - 40 -30||y < 40 + 40) {//500是窗口高度,40是桌子边框,30是球直径,最后一个40是标题栏的高度
// degree = -degree;
// }
//碰到左右边界
// if(x < 40||x > 856 - 40 - 30) {
// degree = 3.14 - degree;
// }
}
void launchFrame(){
setSize(856,500);
setLocation(50,50);
setVisible(true);
while(true) {
repaint();
try {
Thread.sleep(40);//40ms, 1s = 1000ms,大约一秒画25次窗口
}catch(Exception e) {
e.printStackTrace();
}
}
}
public static void main(String args[]){
BallGame game=new BallGame();
game.launchFrame();
}
}
两个图片: