Java代码——运动的小球

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();
}
}

两个图片:

a3dd90c174294750a8a1e6cdbd8fb4b1.png

 

d44624ac998f4d8683c4ffddc980e206.png

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

启明星_Polaris

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值