Código de la clase JFrame:
Código:
Código de la clase JPanel: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:
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 }