赞
踩
实验目的:
在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程序开发的知识,创建了一个弹弹球窗口。除此之外,还运用了多线程的知识去实现小球到处运动,撞击到边框要反弹的功能。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。