使用键盘移动图像 - Java [英] Move image using keyboard - Java
问题描述
我想使用键盘箭头键移动我的图像。当我按下箭头键时,它会相应地移动到方向。但是,我需要先点击图像才能移动它。我是否可以知道如何编辑代码,以便在移动之前我不需要单击图像?我还想知道如果图像到达右边后如何使图像显示,反之亦然。
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.
我的代码是:
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();
}
}
});
推荐答案
你看看 KeyBindings ,否则你必须 JComponent#setFocusable()嵌套
图像
的code>,例如移动图像
You have look at KeyBindings, otherwise you have to JComponent#setFocusable()
that nest the Image
, example for Moving Image
这篇关于使用键盘移动图像 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!