一下是书上的代码 好多人一定看过 请高手简答一下我在代码中的注释中提出的问题import java.awt.geom.*;public class Ball
{
private static final int XSIZE = 15;
private static final int YSIZE = 15;
private double x = 0;
private double y = 0;
private double dx = 1;
private double dy = 1;

/*
一下的x,dx,y,dy,XSIZE,YSIZE都是什么意思
这些事怎么控制运动的 看不明白
谁能详细的说一下move方法 最好每行代码都解释一下
*/
public void move(Rectangle2D bounds){
x += dx;
y += dy; if(x < bounds.getMinX()){
x = bounds.getMinX();
dx = -dx;
}
if(x + XSIZE >=bounds.getMaxX()){
x = bounds.getMaxX() - XSIZE;
dx = -dx;
}
if(y < bounds.getMinY()){
y = bounds.getMinY();
dy = -dy;
}
if(y + YSIZE >= bounds.getMaxY()){
y = bounds.getMaxY() - YSIZE;
dy = -dy;
}
}
public Ellipse2D getShape(){
return new Ellipse2D.Double(x,y,XSIZE,YSIZE);//这句也不懂
}
}
以下是全部代码
主方法在这个类中import java.awt.*;
import java.awt.event.*;
import javax.swing.*;public class Bounce
{
public static void main(String args[]){
JFrame frame = new BounceFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}class BounceFrame extends JFrame
{
private BallComponent comp;
private static final int DEFAULT_WIDTH = 450;
private static final int DEFAULT_HEIGHT = 350;
public static final int STEPS = 1000;
public static final int DELAY = 3; public BounceFrame(){
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
setTitle("Bounce"); comp = new BallComponent();
add(comp,BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel,"start",new ActionListener(){

public void actionPerformed(ActionEvent event){
addBall();
}
}); addButton(buttonPanel,"close",new ActionListener(){
public void actionPerformed(ActionEvent event){
System.exit(0);
}
});
add(buttonPanel,BorderLayout.SOUTH);
}
public void addButton(Container c,String title,ActionListener listener){
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
} public void addBall(){
try
{
Ball ball = new Ball();
comp.add(ball); for(int i = 1; i <= STEPS; i++){
ball.move(comp.getBounds());
comp.paint(comp.getGraphics());
Thread.sleep(DELAY);
}
}
catch (Exception e)
{
}
}
}————————————————————————————————————————————import java.awt.*;
import java.util.*;
import javax.swing.*;public class BallComponent extends JPanel
{
private ArrayList<Ball> balls = new ArrayList<Ball>(); public void add(Ball b){
balls.add(b);
} public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for(Ball b: balls){
g2.fill(b.getShape());
}
}
}

解决方案 »

  1.   

    x,y 图形所在的横纵坐标
    dx,dy 图形的移动“速度”,即每个运行周期中图形移动速度的x和y分量
    XSIZE,YSIZE 图形本身的长宽代码简单说,就是:先在x,y处画一个图形,然后按照下面的动作做循环:
    1、根据dx和dy计算出图形所在的下一个位置;
    2、擦掉原来画上去的图形;
    3、在第1步所计算出来的位置重新绘制新图形;
    4、如果图形超过了所设置的限定区域的边界,则按照“光反射”的方式反弹回来继续移动。