本文主要是介绍Java Applet实现红色反弹球程序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
编写图形界面程序,显示一个红色反弹球的程序,当该球撞击Applet边框时,它应从边框弹回并以相反方向45°运动。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.applet.*;class MyPanel extends JPanel implements Runnable {ThreadDome ud = null;public MyPanel() {ud = new ThreadDome();Thread t = new Thread(ud);t.start();}public void paint(Graphics g) {super.paint(g);setBackground(Color.white);setForeground(Color.white);g.fillOval(0, 0, 20, 20);this.drawBall(ud.ball.getX(), ud.ball.getY(), ud.ball.getWidth(), ud.ball.getHeight(), g);}public void drawBall(int x, int y, int width, int height, Graphics g) {g.setColor(Color.red);g.fillOval(x, y, width, height);}public void run() {while (true) {try {Thread.sleep(5);} catch (Exception e) {e.printStackTrace();}this.repaint();}}
}class Ball {int x;int y;int width;int height;int x_speed = 2;int y_speed = 2;public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public int getWidth() {return width;}public void setWidth(int width) {this.width = width;}public int getHeight() {return height;}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 ThreadDome implements Runnable {Ball ball = new Ball(100, 200, 20, 20);public void run() {while (true) {try {Thread.sleep(5);} catch (Exception e) {e.printStackTrace();}ball.x += ball.x_speed;ball.y += ball.y_speed;if (ball.getX() > 400 || ball.getX() < 0) {ball.x_speed = -ball.x_speed;}if (ball.getY() > 400 || ball.getY() < 0) {ball.y_speed = -ball.y_speed;}}}
}public class Homework04 extends JFrame {MyPanel p = null;public static void main(String[] args) {Homework04 experiment = new Homework04();}public Homework04() {setTitle("弹弹球窗口");p = new MyPanel();Thread ud = new Thread(p);ud.start();this.add(p);this.setSize(400, 400);this.setVisible(true);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}
}
这篇关于Java Applet实现红色反弹球程序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!