Ver Mensaje Individual
  #1 (permalink)  
Antiguo 06/10/2016, 11:40
fran321
 
Fecha de Ingreso: octubre-2007
Mensajes: 57
Antigüedad: 16 años, 6 meses
Puntos: 0
Combinar evento de teclado con un hilo

Intento mover un rectángulo en un JPanel (que es parte de un JFrame) a derecha e izquierda con las flechas del teclado. Un evento capta la pulsación y traslada el cálculo a un hilo. Pulsando una de las teclas, un while asegura que el rectángulo llega hasta el límite del JPanel sin tener que mantener apretado. Si esperas que llegue y pulsas la tecla contraria, se observa que funciona perfectamente. Pero si interrumpes el movimiento a mitad y quieres cambiar de dirección empieza a parpadear. No encuentro dónde está el error, aunque intuyo que los dos while trabajan al mismo tiempo. No sé cómo arreglarlo.

Código de la clase JFrame:

Código:
package Juego;

public class RaquetaFrame extends javax.swing.JFrame {

    public RaquetaFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    ______________
    Generated Code
    ______________
    
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        _____________________________________
        Look and feel setting code (optional)
        _____________________________________
        
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RaquetaFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private Juego.RaquetaPanel raquetaPanel1;
    // End of variables declaration                   
}
Código de la clase JPanel:

Código:
package Juego;

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JOptionPane;

public class RaquetaPanel extends javax.swing.JPanel implements Runnable {
    
    int xRaqueta = 200;
    Thread hiloRaqueta;
    int teclaPulsada;
    
    
    public RaquetaPanel() {
        initComponents();
        setFocusable(true);
    }
    
    @Override
    public void paint(Graphics g){
        g.setColor(getBackground());
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(Color.WHITE);
        g.fillRect(xRaqueta, 350, 100, 10);
    }

    @SuppressWarnings("unchecked")
    ______________
    Generated Code
    ______________
    
    private void formKeyPressed(java.awt.event.KeyEvent evt) {                                
        hiloRaqueta = new Thread(this);
        if (evt.getKeyCode() == evt.VK_RIGHT) {
            teclaPulsada = 1;
        }
        if (evt.getKeyCode() == evt.VK_LEFT) {
            teclaPulsada = -1;
        }
        hiloRaqueta.start();
    }                               

    @Override
    public void run() {
        try {
            if (teclaPulsada == 1) {
                while (xRaqueta < getWidth() - 100) {
                    xRaqueta += 20;
                    repaint();
                    Thread.sleep(30);
                }
            }
            if (teclaPulsada == -1) {
                while (xRaqueta > 0) {
                    xRaqueta -= 20;
                    repaint();
                    Thread.sleep(30);
                }
            }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, e);
            }
    }


    // Variables declaration - do not modify                     
    // End of variables declaration                   
}