JLabel移动的问题
单方向移动正常,但上下移动时一按左右键或者左右移动时一按上下键就会复位到初始坐标。代码如下:
程序代码:
public void keyPressed(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_UP) { tank.setIcon(new ImageIcon(getClass().getResource("/Tank_u.png"))); tank.setBounds(tank.getX(),tank.getY()-10,tank.getWidth(),tank.getHeight()); } else if(e.getKeyCode()==KeyEvent.VK_DOWN) { tank.setIcon(new ImageIcon(getClass().getResource("/Tank_d.png"))); tank.setBounds(tank.getX(),tank.getY()+10,tank.getWidth(),tank.getHeight()); } else if(e.getKeyCode()==KeyEvent.VK_LEFT) { tank.setIcon(new ImageIcon(getClass().getResource("/Tank_l.png"))); tank.setBounds(tank.getX()-10,tank.getY(),tank.getWidth(),tank.getHeight()); } else if(e.getKeyCode()==KeyEvent.VK_RIGHT) { tank.setIcon(new ImageIcon(getClass().getResource("/Tank_r.png"))); tank.setBounds(tank.getX()+10,tank.getY(),tank.getWidth(),tank.getHeight()); } }描述:
初始位置:(370,600,50,75)
按上键后:(380,600,50,75)
按上键后:(390,600,50,75)
按上键后:(400,600,50,75)
按下键后:(390,600,50,75)
按左键后:(370,590,50,75)//此时位置还原了