我试图让我的箭头键顺利移动。然而,在大多数情况下,当第一次按下箭头键时,代码会跳转到 jpanel 的左上角,然后执行我想要的操作。我怎样才能让它在第一次箭头推动时停止跳跃?
谢谢你的帮助。
public class myJPanel0 extends JPanel implements KeyListener
//This panel will contain the game
{
JButton menu;
Image myImage;
Graphics g;
myJPanel1 p1;
JButton lion = new JButton(new ImageIcon("images/lion.jpg"));
int x =100;
int y = 100;
public myJPanel0(myJPanel1 informedp1)
{
super();
setLayout(null);
p1 = informedp1;
setBackground(Color.MAGENTA);
menu = new JButton("Menu");
// lion.setSize(49,49);
lion.setBounds(296,355,49,80);
menu.setBounds(new Rectangle(250,5,80,30));
add(menu);
add(lion);
setFocusable(true);
addKeyListener(this);
}
public void paintComponent(Graphics g)
{
if(p1.myImage1 == 1)
{
super.paintComponent(g);
Image myImage = Toolkit.getDefaultToolkit().getImage("images/snow.jpg");//Place holder for now, we can come up with our own image.
g.drawImage(myImage, 0, 0,680,460, this);
requestFocusInWindow();
}else if(p1.myImage1 == 2)
{
super.paintComponent(g);
Image myImage = Toolkit.getDefaultToolkit().getImage("images/grass.jpg");//Place holder for now, we can come up with our own image.
g.drawImage(myImage, 0, 0,680,460, this);
requestFocusInWindow();
}
else{
super.paintComponent(g);
Image myImage = Toolkit.getDefaultToolkit().getImage("images/stone.jpg");//Place holder for now, we can come up with our own image.
g.drawImage(myImage, 0, 0,680,460, this);
requestFocusInWindow();
}
}
public void keyPressed(KeyEvent evt)
{
System.out.println("Key pressed");
int kk = evt.getKeyCode();
if(kk == evt.VK_LEFT) {x=x-49;}
else if(kk == evt.VK_RIGHT) {x=x+49;}
else if(kk == evt.VK_UP) {y=y-50;}
else if(kk == evt.VK_DOWN) {y=y+50;}
lion.setBounds(x,y,45,75);
}
public void keyReleased(KeyEvent evt) { }
public void keyTyped(KeyEvent evt) { }
}