Mover un botón con las flechas en Java

Resuelto
WeWillNeverForget_11.9.2001 -  
No translation requests here. Demande-t-on une traduction espagnole de ce texte? Si oui, voici la traduction fidèle: Hola,
me gustaría saber cómo mover un botón (de derecha a izquierda) con las flechas en Java. intenté algo pero no funciona:

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 Si au contraire vous vouliez une aide technique en français sur le code Java, dites-moi et je vous réponds directement.

1 respuesta

  • Votos
  • Fecha
  • Fecha descendente
  1. Moderador
    La confianza no excluye el control
    1. Muchas gracias! ¿Existe alguna forma de aumentar la velocidad de desplazamiento sin el pequeño tirón que aparece al aumentar el valor de p.x?
    2. Moderador
      No estoy seguro de entender qué quieres decir por “accoup”, pero puedes intentar acumular las pulsaciones para aumentar la distancia a mover cada vez. Por ejemplo aumentando un 5%

      button.addKeyListener(new KeyListener() { private double dp = 1; @Override public void keyPressed(KeyEvent e) { Point p = button.getLocation(); switch (e.getKeyCode()) { case KeyEvent.VK_RIGHT: button.setLocation(p.x+(int) dp, p.y); break; case KeyEvent.VK_LEFT: button.setLocation(p.x-(int) dp, p.y); break; case KeyEvent.VK_UP: button.setLocation(p.x, p.y-(int) dp); break; case KeyEvent.VK_DOWN: button.setLocation(p.x, p.y+(int) dp); break; } dp *= 1.05; } @Override public void keyReleased(KeyEvent e) { dp = 1; } public void keyTyped(KeyEvent e) {} });