简体   繁体   English

使用键盘移动图像 - 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. 我还想知道如果图像一旦到达右侧就会从左侧出现,反之亦然。

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

 }); 

你看看KeyBindings ,否则你必须嵌套Image JComponent#setFocusable()运动图像的例子

Collect.requestFocusInWindow();

requestFocusInWindow() .. requestFocusInWindow() ..

Requests that this Component get the input focus, if this Component's top-level ancestor is already the focused Window. 如果此Component的顶级祖先已经是焦点窗口请求此Component获取输入焦点

Make sure to call that only after the main window is visible and has the focus. 确保仅在主窗口可见并具有焦点后才调用它。

KeyListeners only work when the component which has the listener has focus . KeyListeners仅在具有侦听器的组件具有焦点时才起作用。 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. 您可以将侦听器添加到其他内容或强制焦点保留在外框之类的内容上,方法是使用焦点侦听器在丢失时重新获得焦点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM