网站建设资讯

NEWS

网站建设资讯

包含java让圆反复碰撞代码的词条

java小球碰撞窗体边缘来回反弹的代码

import java.awt.Color;

网站建设哪家好,找创新互联公司!专注于网页设计、网站建设、微信开发、小程序定制开发、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了七台河免费建站欢迎大家使用!

import java.awt.Graphics;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.util.Random;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class RunningBallDemo extends JFrame {

public static void main(String args[]) {

new RunningBallDemo();

}

public RunningBallDemo() {

Ball ballPanel = new Ball(5, 5);

getContentPane().add(ballPanel);

setBackground(Color.BLACK);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

setSize(350, 350);

setVisible(true);

Thread thread1 = new Thread(ballPanel);

thread1.start();

}

}

class Ball extends JPanel implements Runnable {

int rgb = 0;

Color color;

int x, y;

int dx = 5, dy = 5;

Ball(int x, int y) {

this.x = x;

this.y = y;

}

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

setBackground(Color.BLACK);

g.setColor(color);

g.fillOval(x, y, 50, 50);

}

public void run() {

while (true) {

if (x = 0) {

dx = 5;

updateBallColor();

} else if ((x + 50) = getWidth()) {

dx = -5;

updateBallColor();

}

if (y = 0) {

dy = 5;

updateBallColor();

} else if ((y + 50) = getHeight()) {

dy = -5;

updateBallColor();

}

x = x + dx;

y = y + dy;

repaint();

try {

Thread.sleep(25);

} catch (InterruptedException e) {

;

}

}

}

public void updateBallColor() {

rgb = new Random().nextInt();

color = new Color(rgb);

}

}

JAVA用repaint方法在窗格内实现小球的来回碰撞,怎么在窗格边缘改变小球的运动方向呢?

public class DrawBall extends JFrame {

int x, y, width, height;

Color c;

int incX = 10;//X方向增量

int incY = 10;//Y方向增量

public DrawBall() {

super("寂寞高手不寂寞");

setSize(800, 600);

setVisible(true);

x = 0;

y = 0;

width = height = 50;

c = new Color(255, 0, 0);

}

public static void main(String[] args) {

DrawBall a = new DrawBall();

}

public void paint(Graphics g) {

Container pane = getContentPane();

Graphics pg = pane.getGraphics();

pg.setColor(Color.WHITE);

pg.fillRect(0, 0, pane.getWidth(), pane.getHeight());

//从这里开始改变小球的运动方向

if (x+width pane.getWidth() || x 0) {//X边界判断

incX *= -1; //增量方向反转

}

if (y+height pane.getHeight() || y 0) {//Y边界判断

incY *= -1;//增量方向反转

}

x = x + incX;

y = y + incY;

pg.setColor(c);

pg.fillOval(x, y, width, height);

try {

Thread.sleep(100);

} catch (InterruptedException E) {

};

repaint();

}

}

Eclipse 写 java小程序。 6个小球碰撞反弹。我知道怎么碰壁反弹。我想要在碰撞过程中小球互相碰撞也反弹。

给小球类定义一个方法:碰撞;然后当周围环境的坐标到球心的距离等于小球的半径时,小球的运动路径算法就应该是轴对称的。先判断之前的运动方向,然后根据运动方向确定新的运动方向。这个其实就是线性方程做小球的运动轨迹而已。


标题名称:包含java让圆反复碰撞代码的词条
标题链接:http://cdweb.net/article/ddsggih.html