Move a button with the arrow keys in Java

Solved
WeWillNeverForget_11.9.2001 -  
KX Posted messages 19031 Status Moderator -
Traduction de leur message en anglais: Hello,
I’d like to know how to move a button (left-right) using the arrow keys in Java. I tried something but it doesn’t work:

public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}

public void keyPressed(KeyEvent e) {
case KeyEvent.VK_RIGHT:
goRight();
break;
case KeyEvent.VK_LEFT:
goLeft();
break;
case KeyEvent.VK_UP:
jump();
break;

}

static int posX = 40;
static int posY = 750;

public int goRight() {
posX = posX+1;
return posX;
}

public int goLeft() {
posX = posX-1;
return posX;
}

public int jump() {

}
/**
* @param args
*/
public static void main(String[] args) {

JButton bouton = new JButton("bouton",(new ImageIcon("xxx.jpg")));
bouton.setLayout(null);
bouton.setBounds(posX,posY,10,20);

JPanel panneauPrincipal = new JPanel();
panneauPrincipal.add(bouton);

JFrame fenetre = new JFrame();
fenetre.setSize(1680, 1050);
fenetre.getContentPane().add(bouton);

fenetre.add(panneauPrincipal);

fenetre.setLocationRelativeTo(null);
fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fenetre.setVisible(true);

}}

Configuration: Mac OS X / Firefox 14.0

1 answer

  1. KX Posted messages 19031 Status Moderator 3 020
     
    Exemple :

    import java.awt.Point; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JButton; import javax.swing.JFrame; public class Test1 { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setLayout(null); frame.setSize(800, 800); final JButton button = new JButton("Bouton"); frame.add(button); button.setBounds(350,380,100,40); button.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { Point p = button.getLocation(); switch (e.getKeyCode()) { case KeyEvent.VK_RIGHT: button.setLocation(p.x+1, p.y); break; case KeyEvent.VK_LEFT: button.setLocation(p.x-1, p.y); break; case KeyEvent.VK_UP: button.setLocation(p.x, p.y-1); break; case KeyEvent.VK_DOWN: button.setLocation(p.x, p.y+1); break; } } public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} }); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }

    --
    La confiance n'exclut pas le contrôle
    -1
    1. WeWillNeverForget_11.9.2001
       
      thank you very much!
      is there a way to increase the movement speed without the small jerk that occurs when you increase the value of p.x?
      0
    2. KX Posted messages 19031 Status Moderator 3 020
       
      I’m not sure I understand what you mean by “accoup” but you can try to accumulate the keys to increase the distance to move each time. For example by increasing it by 5%
      0