Move image using keyboard - Java

人盡茶涼 提交于 2019-11-28 08:20:51

问题


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();
         }
     }

 }); 

回答1:


You have look at KeyBindings, otherwise you have to JComponent#setFocusable() that nest the Image, example for Moving Image




回答2:


Collect.requestFocusInWindow();

requestFocusInWindow()..

Requests that this Component get the input focus, if this Component's top-level ancestor is already the focused Window.

Make sure to call that only after the main window is visible and has the focus.




回答3:


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.



来源:https://stackoverflow.com/questions/8716217/move-image-using-keyboard-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!