我想让我的箭头键顺利移动。然而,在大多数情况下代码都可以工作,当第一次按下箭头键时,它会跳转到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) { }
}
答案 0 :(得分:1)
下一步你的问题:开始时设置lion.setBounds(296,355,49,80);
该对象的位置 296,355 ,但是当您首先按下键时使用int x =100;
int y = 100;
,因此您有这种效果。将x和y更改为int x = 296;
int y = 355;
,它将起作用。