我有一个通过键盘控制的形状,并与计时器相关联。当形状到达某个坐标点时,它会停止计时器。那么我怎样才能将形状重新设置回原来的起始位置,同时将定制的形状留在定时器停止的位置?
public class ForStack extends JPanel implements KeyListener,ActionListener{
Timer t = new Timer(800, this);
int count = 0;
double x = 0, y = 0, velX = 0, velY = 0;
public ForStack (){
t.start();
addKeyListener(this);
setFocusable(true);
}
public void paint(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle2D rectangle = new Rectangle2D.Double(x,y,50, 50);
g2.setColor(Color.BLACK);
g2.fill(rectangle);
int counter = 0;int x = 0; int y = 0;
g.setColor(Color.RED);
if (counter == 0){
do{
g.drawRect(x,y,50,50);
x += 50;
counter++;
}while(counter != 6);
}
x=0;
y=0;
if (counter == 6){
do{
g.drawRect(x,50,50,50);
x += 50;
counter++;
}while(counter != 12);
}
x=0;
y=0;
if (counter == 12){
do{
g.drawRect(x,100,50,50);
x += 50;
counter++;
}while(counter != 18);
}
x=0;
y=0;
if (counter == 18){
do{
g.drawRect(x,150,50,50);
x += 50;
counter++;
}while(counter != 24);
}
x=0;
y=0;
if (counter == 24){
do{
g.drawRect(x,200,50,50);
x += 50;
counter++;
}while(counter != 30);
}
x=0;
y=0;
if (counter == 30){
do{
g.drawRect(x,250,50,50);
x += 50;
counter++;
}while(counter != 36);
}
x=0;
y=0;
if (counter == 36){
do{
g.drawRect(x,300,50,50);
x += 50;
counter++;
}while(counter != 42);
}
x=0;
y=0;
if (counter == 42){
do{
g.drawRect(x,350,50,50);
x += 50;
counter++;
}while(counter != 48);
}
x=0;
y=0;
if (counter == 48){
do{
g.drawRect(x,400,50,50);
x += 50;
counter++;
}while(counter != 54);
}
x=0;
y=0;
if (counter == 54){
do{
g.drawRect(x,450,50,50);
x += 50;
counter++;
}while(counter != 60);
}
}
@Override
public void actionPerformed(ActionEvent e){
if(x == 0 & y == 400 ){
t.stop();
}
repaint();
x += velX;
y += velY;
}
@Override
public void keyPressed(KeyEvent e){
int code = e.getKeyCode();
if (code == KeyEvent.VK_DOWN){
velY += 50;
velX += 0;
}
else if (code == KeyEvent.VK_LEFT){
velX -= 50;
velY = 0;
}
else if (code == KeyEvent.VK_RIGHT){
velX += 50;
velY = 0;
}
}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e){}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new ForStack());
frame.setVisible(true);
frame.setSize(800,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} // end of main
} // end of class
答案 0 :(得分:1)
通常情况下,当一个帖子的代码中有太多错误时,我倾向于远离,因为问题的答案需要太多的修复,并涉及自己破解代码并重构一切。我不打算这样做。我会把它留给你。我只是指出我注意到的事情,并由你来尝试修复。
摆脱所有 while循环。您在paint
方法中包含了 way 过多的逻辑。我真的不知道你要用这个逻辑完成什么,但它只是看起来完全错误。
您可以做的只是保持List
或Rectangles
。如果需要另一个,请在列表中添加新的Rectangle
。其中只有一个会一次动画。所有其余的将驻留在最后一点。使用List
的索引在计时器中,您将检查该索引,并且仅当该索引相等时,它才会设置动画。您应该在paint
方法中遍历List并绘制所有这些。关键是要将你的逻辑与你的绘画分开。
不要覆盖paint
,而是paintComponent
使用Key Bindings代替KeyListener
if(x == 0 & y == 400 ){
这是你真正想要的吗?也许||。如果它是你想要的,你想要使用&&不是&