gpt4 book ai didi

java - 使用箭头键

转载 作者:行者123 更新时间:2023-12-01 13:52:47 26 4
gpt4 key购买 nike

我正在尝试让我的箭头键顺利移动。在大多数情况下,代码都可以工作,但是,当第一次按下箭头键时,它会跳转到 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) { }
}

最佳答案

接下来你的问题:在开始时你设置 lion.setBounds(296,355,49,80);该对象的位置是 296,355,但是当您第一次按键时,您会使用 int x =100;
int y = 100;
,正因为如此,你才有这样的效果。将 x 和 y 更改为 int x = 296;
int y = 355;
这将会起作用。

关于java - 使用箭头键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19841787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com