📄 ball.java
字号:
package day03.ball;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
/**
* 小球类,代表在画布上移动的小球
* @author Administrator
*
*/
public class Ball{
private BallPanel canvas;//画布
private Color color;//小球的颜色
private static final int XSIZE = 30;//小球的X直径
private static final int YSIZE = 30;//小球的Y直径
private int x = 0; //小球所处的座标
private int y = 0;
private int dx = 1; //小球每次移动的步长
private int dy = 1;
public static int CURRENT_NUM=1;//当前小球的编号
private int number;//该小球的编号
public Ball(BallPanel c) {
this(c,Color.black);
}
public Ball(BallPanel c, Color color) {
canvas = c;
this.color = color;
this.number=CURRENT_NUM;
CURRENT_NUM++;
}
/**
* 根据x,y座标绘制当前小球
* @param g2
*/
public void draw(Graphics2D g2) {
if(color != null) g2.setColor(color);
g2.fill(new Ellipse2D.Double(x, y, XSIZE, YSIZE));
g2.setColor(Color.WHITE);
g2.setFont(new Font("",Font.BOLD,16));
g2.drawString(number+"", x+XSIZE/2-5, y+YSIZE/2+5);
}
/**
* 该方法控制小球的移动动作。
* 移动小球其实就是把小球的座标位置改变一下,
* 再调用画布的repaint方法。
*
*/
public void move(){
x += dx; y += dy;
if (x < 0){ x = 0; dx = -dx; }
if (x + XSIZE >= canvas.getWidth()){ x = canvas.getWidth() - XSIZE; dx = -dx; }
if (y < 0){ y = 0; dy = -dy; }
if (y + YSIZE >= canvas.getHeight()) { y = canvas.getHeight() - YSIZE; dy = -dy; }
canvas.repaint();
}
public BallPanel getCanvas() {
return canvas;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -