Como utilizar as teclas direcionais para mover objeto do Swing?

1 resposta
java
D

Estou tentando fazer um game Pong, mas nao consigo mover a barra com as teclas direcionais…

/**
*

  • @author davidleles
    */
    public class PongView extends javax.swing.JFrame implements KeyListener{

    /**

    • Creates new form PongView
      */
      public PongView() {
      initComponents();
      addKeyListener(this);
      }

    //
    private void initComponents() {

    wall = new javax.swing.JPanel();
     bolinha = new javax.swing.JLabel();
     barra = new javax.swing.JLabel();
     jButton1 = new javax.swing.JButton();
    
     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     setBackground(new java.awt.Color(255, 255, 255));
    
     wall.setBackground(new java.awt.Color(0, 0, 0));
    
     bolinha.setBackground(new java.awt.Color(255, 255, 255));
     bolinha.setForeground(new java.awt.Color(255, 255, 255));
     bolinha.setText("O");
    
     barra.setForeground(new java.awt.Color(255, 255, 255));
     barra.setText("------------");
    
     javax.swing.GroupLayout wallLayout = new javax.swing.GroupLayout(wall);
     wall.setLayout(wallLayout);
     wallLayout.setHorizontalGroup(
         wallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(wallLayout.createSequentialGroup()
             .addGap(171, 171, 171)
             .addGroup(wallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                 .addComponent(barra)
                 .addComponent(bolinha))
             .addContainerGap(181, Short.MAX_VALUE))
     );
     wallLayout.setVerticalGroup(
         wallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, wallLayout.createSequentialGroup()
             .addContainerGap(134, Short.MAX_VALUE)
             .addComponent(bolinha)
             .addGap(105, 105, 105)
             .addComponent(barra)
             .addContainerGap())
     );
    
     jButton1.setBackground(new java.awt.Color(153, 153, 153));
     jButton1.setText("Start");
     jButton1.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
             jButton1ActionPerformed(evt);
         }
     });
    
     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
     getContentPane().setLayout(layout);
     layout.setHorizontalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addComponent(wall, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
         .addGroup(layout.createSequentialGroup()
             .addGap(158, 158, 158)
             .addComponent(jButton1))
     );
     layout.setVerticalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(layout.createSequentialGroup()
             .addComponent(wall, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
             .addGap(6, 6, 6)
             .addComponent(jButton1))
     );
    
     pack();
    

    }//

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    
    // TODO add your handling code here:
    
    Contador ct = new Contador(action());
    

    }

    /**

    • @param args the command line arguments
      /
      public static void main(String args[]) {
      /
      Set the Nimbus look and feel /
      //
      /
      If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

      • For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
        */
        try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if (“Nimbus”.equals(info.getName())) {
        javax.swing.UIManager.setLookAndFeel(info.getClassName());
        break;
        }
        }
        } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(PongView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(PongView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(PongView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(PongView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //
      /* Create and display the form */
      
      java.awt.EventQueue.invokeLater(new Runnable() {
      
      public void run() {
      
      new PongView().setVisible(true);
       }
      

      });
      }

    public ActionListener action (){

    ActionListener action = new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
             tarefas();
             
         }
     };
     
     return action;
    

    }

    public void tarefas(){
    moveBolinha();

    }

    /**

    • variaveis globais a serem usadas no moveBolinha
      */
      int inc_x = 10;
      int inc_y = 10;
    public void moveBolinha(){
    
    int bol_x = bolinha.getX();
    
    int bol_y = bolinha.getY();
    
    int size_bol = bolinha.getWidth();
    
    int wall_x = wall.getWidth()-5;
    
    int wall_y = wall.getHeight()-10;
    
    /**
      * CONDIÇÕES
      */
     if(bol_x >= wall_x - size_bol){
        inc_x = -inc_x;
     }
     if(bol_x <= size_bol){
        inc_x = -inc_x;
     }
     if(bol_y >= wall_y - size_bol){
        inc_y = -inc_y;
     }
     if(bol_y <= size_bol){
        inc_y = -inc_y;
     }
    bolinha.setLocation(bol_x += inc_x, bol_y += inc_y);
    

    }

    /**

    • Controlando a barra
      */
    public void barra_press_right(){
    
    barra.setLocation(barra.getX()+2, barra.getY());
    
    }
    
    public void barra_press_left(){
    
    barra.setLocation(barra.getX()-2, barra.getY());
    
    }
    
    /**
    * 
    * TECLAS PRESSIONADAS PARA MOVER A BARRA
    */
    
    // Variables declaration - do not modify
    
    private javax.swing.JLabel barra;
    
    private javax.swing.JLabel bolinha;
    
    private javax.swing.JButton jButton1;
    
    private javax.swing.JPanel wall;
    
    // End of variables declaration
    

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    <a class="mention" href="/u/override">@Override</a>
    
    public void keyPressed(KeyEvent e) {
    
    if(e.getKeyCode() == VK_RIGHT){
    
    System.out.println(“DIREITAAA”);
    
    }
    
    }
    

}

1 Resposta

H

Para mover objetos usando o swing tem de utilizar o graphics2d, usar paint e repaint, surigo que você pegue o exemplo de um jogo simples pronto na internet e tente fazer algumas alterações para ir entendendo como funciona, mas lembrando que fazer jogo em Java swing não é a melhor opção, da muito trabalho, da muitos erros e muitos bugs.

Criado 11 de abril de 2018
Ultima resposta 11 de abr. de 2018
Respostas 1
Participantes 2