Moving an Image Using the Keyboard - Java

I wanted to move my image using the keyboard arrow keys. when i press the arrow keys, it moves according to the direction. However, I need to click on the image before I can transfer it. Can I learn how to edit the code so that I don’t have to click the image before it can be moved? I would also like to know how to make the image appear on the left when it reaches the 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(); } } }); 
+4
source share
3 answers

You are looking at KeyBindings , otherwise you must JComponent#setFocusable() insert Image , an example for Moving an image

+4
source
 Collect.requestFocusInWindow(); 

requestFocusInWindow() ..

Requires this component to gain input focus if this top-level ancestor is already focused.

Be sure to call this only after the main window is visible and has focus.

+3
source

KeyListeners only work when the component that has the listener has focus . You focus on what Collect seems to be by clicking on it. Then the listener works. You can add a listener to other things or make the focus stay on something like an external frame, using the focus listener to restore focus when it is lost.

+1
source

Source: https://habr.com/ru/post/1389116/


All Articles