欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

编写图形界面程序,显示一个红色反弹球的程序,当该球撞击Applet边框时,它应从边框弹回并以相反方向45°运动。

发布时间:2025/3/15 编程问答 32 豆豆
生活随笔 收集整理的这篇文章主要介绍了 编写图形界面程序,显示一个红色反弹球的程序,当该球撞击Applet边框时,它应从边框弹回并以相反方向45°运动。 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

编写图形界面程序,显示一个红色反弹球的程序,当该球撞击Applet边框时,它应从边框弹回并以相反方向45°运动。

import javax.swing.*; import java.awt.*;class BallPanel extends JPanel implements Runnable {ball_move BM = null;public BallPanel() {BM = new ball_move();Thread t = new Thread(BM);t.start();//这一行不加会导致画面停止不动}public void paint(Graphics g) {//画球super.paint(g);setBackground(Color.white);setForeground(Color.white);g.fillOval(0, 0, 20, 20);//fillOval(int x,int y,int width,int height)使用度当前颜色填充外接指定矩形框的椭圆。this.drawBall(BM.ball.getX(), BM.ball.getY(), BM.ball.getWidth(), BM.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();//数据在ball_move中设置}} } //球的参数 class Ball {int x,y,width,height;int x_speed = 1,y_speed = 1;public void setX(int x) {this.x = x;}public int getX() {return x;}public void setY(int y) {this.y = y;}public int getY() {return y;}public void setWidth(int width) {this.width = width;}public int getWidth() {return width;}public void setHeight(int height) {this.height = height;}public int getHeight() {return height;}public Ball(int x, int y, int width, int height) {this.x = x;this.y = y;this.width = width;this.height = height;} } //球移动的数据,并在BallPanel不断重画 class ball_move implements Runnable {Ball ball = new Ball(0, 100, 40, 40);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 BallFrame extends JFrame {public static void main(String[] args) {BallFrame experiment = new BallFrame();}public BallFrame() {BallPanel p = new BallPanel();Thread BM = new Thread(p);//运动的代码BM.start();this.add(p);this.setSize(450, 480);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);} }

总结

以上是生活随笔为你收集整理的编写图形界面程序,显示一个红色反弹球的程序,当该球撞击Applet边框时,它应从边框弹回并以相反方向45°运动。的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。