编写图形界面程序,显示一个红色反弹球的程序,当该球撞击Applet边框时,它应从边框弹回并以相反方向45°运动。
生活随笔
收集整理的這篇文章主要介紹了
编写图形界面程序,显示一个红色反弹球的程序,当该球撞击Applet边框时,它应从边框弹回并以相反方向45°运动。
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
編寫(xiě)圖形界面程序,顯示一個(gè)紅色反彈球的程序,當(dāng)該球撞擊Applet邊框時(shí),它應(yīng)從邊框彈回并以相反方向45°運(yùn)動(dòng)。
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();//這一行不加會(huì)導(dǎo)致畫(huà)面停止不動(dòng)}public void paint(Graphics g) {//畫(huà)球super.paint(g);setBackground(Color.white);setForeground(Color.white);g.fillOval(0, 0, 20, 20);//fillOval(int x,int y,int width,int height)使用度當(dāng)前顏色填充外接指定矩形框的橢圓。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();//數(shù)據(jù)在ball_move中設(shè)置}} } //球的參數(shù) 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;} } //球移動(dòng)的數(shù)據(jù),并在BallPanel不斷重畫(huà) 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);//運(yùn)動(dòng)的代碼BM.start();this.add(p);this.setSize(450, 480);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);} }總結(jié)
以上是生活随笔為你收集整理的编写图形界面程序,显示一个红色反弹球的程序,当该球撞击Applet边框时,它应从边框弹回并以相反方向45°运动。的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: app 后台_uni星茫UI V3.0更
- 下一篇: rdkafka线程过多_Kafka/Ro