我想使用鍵盤箭頭鍵移動圖像。當我按下箭頭鍵時,它會相應地朝着方向移動。但是,我需要點擊圖片才能移動它。我可否知道如何編輯代碼,以便在移動圖像之前不需要單擊圖像?我也想知道如何讓圖像從左側出現,一旦到達右側,反之亦然。使用鍵盤移動圖像 - 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();
}
}
});
1)爲了更好地提供幫助,請發佈[SSCCE](http://sscce.org/)。 2)請學習常用的Java命名法(例如'Collect' - >'collect')並將其用於代碼示例中。 – 2012-01-03 17:50:32