编写图形界面程序,显示一个红色反弹球的程序,当该球撞击Applet边框时,它应从边框弹回并以相反方向45°运动。
生活随笔
收集整理的這篇文章主要介紹了
编写图形界面程序,显示一个红色反弹球的程序,当该球撞击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°运动。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: app 后台_uni星茫UI V3.0更
- 下一篇: rdkafka线程过多_Kafka/Ro