此方法用于绘制机器人&我想每隔1秒绘制一次,但要延迟一个接一个地绘制机器人(并非一次全部绘制)。我使用了计时器,但不起作用,因此如何使用它我的情况, 机器人代表矩形并向目标移动
public void paint(double[] position, double direction, int[][] pixels, double robotHalfDiagonalDistance) {
double[] corner1, corner2, corner3, corner4;
final Graphics2D g = (Graphics2D) image.getGraphics();
super.paint(g);
corner1 = new double[2]; corner2 = new double[2];corner3 = new double[2]; corner4 = new double[2];
corner1[0] = (position[0] + robotHalfDiagonalDistance * Math.sin(direction - pi / 4));
corner1[1] = (position[1] + robotHalfDiagonalDistance * Math.cos(direction - pi / 4));
corner2[0] = (position[0] + robotHalfDiagonalDistance * Math.sin(direction + pi / 4));
corner2[1] = (position[1] + robotHalfDiagonalDistance * Math.cos(direction + pi / 4));
corner3[0] = (position[0] + robotHalfDiagonalDistance * Math.sin(direction - pi / 4 + pi));
corner3[1] = (position[1] + robotHalfDiagonalDistance * Math.cos(direction - pi / 4 + pi));
corner4[0] = (position[0] + robotHalfDiagonalDistance * Math.sin(direction + pi / 4 + pi));
corner4[1] = (position[1] + robotHalfDiagonalDistance * Math.cos(direction + pi / 4 + pi));
int value0 = (int) corner1[0];int value1 = (int) corner1[1];
final int[] corner1n = {value0, value1};
int value00 = (int) corner2[0]; int value11 = (int) corner2[1];
final int[] corner2n = {value00, value11};
int value000 = (int) corner3[0];int value111 = (int) corner3[1];
final int[] corner3n = {value000, value111};
int value0000 = (int) corner4[0];int value1111 = (int) corner4[1];
final int[] corner4n = {value0000, value1111};
if (pixels[corner1n[0]][corner1n[1]] == 1 && pixels[corner2n[0]][corner2n[1]] == 1 && pixels[corner3n[0]][corner3n[1]] == 1
&& pixels[corner4n[0]][corner4n[1]] == 1) {
g.setColor(Color.RED);
//g.setStroke(new BasicStroke(2));
Timer t = new Timer(1000,new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
//bottom
g.drawLine(corner1n[0], corner1n[1], corner2n[0], corner2n[1]);
//right
g.drawLine(corner2n[0], corner2n[1], corner3n[0], corner3n[1]);
//up
g.drawLine(corner3n[0], corner3n[1], corner4n[0], corner4n[1]);
///left
g.drawLine(corner4n[0], corner4n[1], corner1n[0], corner1n[1]);
//repaint();
}
});
t.start();
}
else{
System.err.println("collision ");
}
}
请帮助我
答案 0 :(得分:1)
首先,您需要创建a swing timer,然后安排指定的任务(绘图)以重复执行固定速率delay
:
import javax.swing.Timer;
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// Perform a task repeatedly
}
};
new Timer(delay, taskPerformer).start();
计时器启动后,将等待初始延迟,然后将其第一个ActionEvent触发给已注册的侦听器 要进一步阅读该主题,请查看上面的链接。