Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

 }); 
like image 756
KYQ Avatar asked Feb 22 '23 23:02

KYQ


1 Answers

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

like image 85
mKorbel Avatar answered Feb 26 '23 20:02

mKorbel