大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
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);
}
}
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();
}
}
给小球类定义一个方法:碰撞;然后当周围环境的坐标到球心的距离等于小球的半径时,小球的运动路径算法就应该是轴对称的。先判断之前的运动方向,然后根据运动方向确定新的运动方向。这个其实就是线性方程做小球的运动轨迹而已。