《Java程序设计》实 验 报 告---- java Applet 小程序

实验目的:
在Eclipse下编辑、编译、运行、调试关于java Applet小程序。

实验内容:
编写一个Applet内部显示一个蓝色反弹球的程序,通过一个事件使该球开始运动,在该球撞击Applet边框时,它应从边框弹回并以相反的方向运动。
源程序:
Sy4.java 具体代码如下:

package sy4;

import java.awt.*;

import javax.swing.*;

import java.applet.*;

class Ball{
	int x;//小球所在x坐标
	int y;//小球所在y坐标
	int width;
	int height;
		
	public int getX() {
		return x;
	}
	public int getY() {
		return y;
	}
	public int getWidth() {
		return width;
	}
	public int getHeight() {
		return height;
	}
	
	public void setX(int x) {
		this.x = x;
	}
	public void setY(int y) {
		this.y = y;
	}
	public void setWidth(int width) {
		this.width = width;
	}
	public void setHeight(int height) {
		this.height = height;
	}
	
	public Ball(int x, int y, int width, int height) {
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}
}
//球不断运动,不断重画
class Demo implements Runnable{
	int dx = (int)(Math.random()*10)%2+3;
	int dy = (int)(Math.random()*10)%2+3;
	Ball ball = new Ball(0, 200, 20, 20);
	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(5);
			} catch (Exception e) {
				e.printStackTrace();
			}
			ball.x += dx;
			ball.y += dy;
			if (ball.getX() > 400 || ball.getX() < 0) {
				dx = -dx;
			}
			if (ball.getY() > 400 || ball.getY() < 0) {
				dy = -dy;
			}
		}
	}
	
}

class MyApplet extends Applet implements Runnable{
	Demo d = null;
	public MyApplet() {
		d = new Demo();
		Thread t = new Thread(d);
		t.start();
	}
	public void paint(Graphics g) {//画球
		g.setColor(Color.blue);
		g.fillOval(d.ball.getX(),d.ball.getY(),d.ball.getWidth(),d.ball.getHeight());
	}
	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(5);
			} catch (Exception e) {
				e.printStackTrace();
			}
			this.repaint();
		}
	}
	
}

public class Sy4 extends JFrame{
	MyApplet m = null;
	public Sy4() {
		setTitle("弹弹球窗口");
	    m = new MyApplet();
		Thread n = new Thread(m);
		n.start();
		this.add(m);
		this.setSize(400, 400);
		this.setVisible(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	public static void main(String[] args) {
		Sy4 s = new Sy4();
	}
}

实验结果与体会:
结果截图如下:
在这里插入图片描述

体会:在本次实验中,我使用了有关Applet程序开发的知识,创建了一个弹弹球窗口。除此之外,还运用了多线程的知识去实现小球到处运动,撞击到边框要反弹的功能。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值