使用键盘移动图像 - Java
我想使用键盘箭头键移动图像。当我按下箭头键时,它会按照方向移动。但是,我需要先单击图像才能移动它。我可以知道如何编辑代码,这样我就不需要单击图像就可以移动它吗?我还想知道如何使图像到达右侧后从左侧出现,反之亦然。
我的代码是:
Collect.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyCode() == KeyEvent.VK_LEFT)
{
Collect.setLocation(Collect.getX()-8,Collect.getY());
repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_RIGHT)
{
Collect.setLocation(Collect.getX()+8,Collect.getY());
repaint();
}
}
});
Collect.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
if(me.getClickCount() == 1)
{
boolean dd = Collect.isOptimizedDrawingEnabled();
boolean ff = Collect.requestFocusInWindow();
repaint();
}
}
});
I wanted to move my image using keyboard arrow keys. when I pressed the arrow keys it moves accordingly to the direction. However, I need to click on the image before able to move it. May I know how to edit the code such that I do not need to click on the image before able to move it? I would also like to know how to make the image appear from the left once it reaches right and vice versa.
My codes are :
Collect.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyCode() == KeyEvent.VK_LEFT)
{
Collect.setLocation(Collect.getX()-8,Collect.getY());
repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_RIGHT)
{
Collect.setLocation(Collect.getX()+8,Collect.getY());
repaint();
}
}
});
Collect.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
if(me.getClickCount() == 1)
{
boolean dd = Collect.isOptimizedDrawingEnabled();
boolean ff = Collect.requestFocusInWindow();
repaint();
}
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您已经查看了KeyBindings,否则您必须
JComponent#setFocusable()
嵌套Image
,例如 移动图像You have look at KeyBindings, otherwise you have to
JComponent#setFocusable()
that nest theImage
, example for Moving ImagerequestFocusInWindow()< /代码>
..
请确保仅在主窗口可见并具有焦点。
requestFocusInWindow()
..Make sure to call that only after the main window is visible and has the focus.
KeyListener 仅在具有侦听器的组件具有焦点时才起作用。通过单击,您将焦点集中到看似“收集”的内容上。然后监听器就开始工作了。您可以将侦听器添加到其他对象,或者通过使用焦点侦听器在焦点丢失时重新获得焦点,强制焦点保留在外框等对象上。
KeyListeners only work when the component which has the listener has focus. You are giving focus to what appears to be Collect by clicking on it. Then the listener works. You can add the listener to other things or force focus to remain on something like the outer frame by using a focus listener to regain focus whenever it is lost.