# Key Listener reagiert nicht !



## DerMeister2010 (16. Mai 2012)

Ich bin gerade dabei tetris zu programmieren (Anfangsphase) habe allerdings ein Problem der KeyListener funktioniert nicht und ich weiß nicht warum bitte um Hilfe 

```
public class GameGUI extends javax.swing.JFrame implements Runnable, KeyListener {

    int gamefield[][] = new int[11][21];
    Game game;
    Thread t;
    int x = 0;
    int y = 10;
    int gf_x=0;
    int gf_y=0;
    Graphics2D g;

    /**
     * Creates new form GameGUI
     */
    public GameGUI() {
        initComponents();
      
        try {
            UIManager.setLookAndFeel(new NimbusLookAndFeel());
            SwingUtilities.updateComponentTreeUI(this);
        } catch (UnsupportedLookAndFeelException ex) {
        }
        
        this.addKeyListener(this);


    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jpyou = new javax.swing.JPanel();
        jpopponent = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jpyou.setBorder(javax.swing.BorderFactory.createTitledBorder("You"));

        javax.swing.GroupLayout jpyouLayout = new javax.swing.GroupLayout(jpyou);
        jpyou.setLayout(jpyouLayout);
        jpyouLayout.setHorizontalGroup(
            jpyouLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 419, Short.MAX_VALUE)
        );
        jpyouLayout.setVerticalGroup(
            jpyouLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jpopponent.setBorder(javax.swing.BorderFactory.createTitledBorder("Opponent"));

        javax.swing.GroupLayout jpopponentLayout = new javax.swing.GroupLayout(jpopponent);
        jpopponent.setLayout(jpopponentLayout);
        jpopponentLayout.setHorizontalGroup(
            jpopponentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jpopponentLayout.setVerticalGroup(
            jpopponentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jPanel3.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 79, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 54, Short.MAX_VALUE)
        );

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Time");

        jButton1.setText("Start");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpyou, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(46, 46, 46)
                .addComponent(jpopponent, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(70, 70, 70)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(292, 292, 292))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpyou, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jpopponent, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 528, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
      
         game = new Game();
         for(int i=0;i<11;i++)
        {
            gamefield[i][20]=1;
        }
        t = new Thread(this);
        t.start();
       
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * [url=http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html]How to Set the Look and Feel (The Java™ Tutorials > Creating a GUI With JFC/Swing > Modifying the Look and Feel)[/url]
         */
        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(GameGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GameGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GameGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GameGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new GameGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jpopponent;
    private javax.swing.JPanel jpyou;
    // End of variables declaration

    @Override
    public void run() {
        x = this.jpyou.getWidth() / 2;
        y = 20;
        gf_x=5;
        gf_y=0;
        
        while (!t.isInterrupted()) {
             g = (Graphics2D) this.jpyou.getGraphics();
            try {

                String stone = game.getStone();
//                if(stone.equals("viereck"))
//                {
//                  x=5;y=0;
//                  gamefield[x][y]=1;
//                  gamefield[x+1][y]=1;
//                  gamefield[x][y+1]=1;
//                  gamefield[x+1][y+1]=1;
//                }else if(stone.equals("L"))
//                {
//                      x=5;y=0;
//                  gamefield[x][y]=1;
//                  gamefield[x][y+1]=1;
//                  gamefield[x][y+2]=1;
//                  gamefield[x+1][y+2]=1;
//                }else if(stone.equals("J"))
//                {
//                      x=5;y=0;
//                  gamefield[x][y]=1;
//                  gamefield[x][y+1]=1;
//                  gamefield[x][y+2]=1;
//                  gamefield[x-1][y+2]=1;
//                }else if(stone.equals("z-left"))
//                {
//                      x=5;y=0;
//                  gamefield[x][y]=1;
//                  gamefield[x+1][y]=1;
//                  gamefield[x+1][y+1]=1;
//                  gamefield[x+2][y+1]=1;
//                }else if(stone.equals("z-right"))
//                {
//                      x=5;y=0;
//                  gamefield[x][y]=1;
//                  gamefield[x+1][y]=1;
//                  gamefield[x][y+1]=1;
//                  gamefield[x-1][y+1]=1;
//                }else if(stone.equals("t"))
//                {
//                      x=5;y=0;
//                  gamefield[x][y]=1;
//                  gamefield[x-1][y+1]=1;
//                  gamefield[x][y+1]=1;
//                  gamefield[x+1][y+1]=1;
//                }else if(stone.equals("I"))
//                {
//                      x=3;y=0;
//                  gamefield[x][y]=1;
//                  gamefield[x+1][y]=1;
//                  gamefield[x+2][y]=1;
//                  gamefield[x+3][y]=1;
//                }
                    
                    if(gamefield[gf_x][gf_y+1]==1)
                    {
                        gamefield[gf_x][gf_y-1]=1;
                        y=20;gf_y=0;
                    }
                    
                    g.setXORMode(Color.white);
                    g.setColor(Color.red);
                    g.fillRect(x, y, 18, 18);
                    g.fillRect(x + 20, y, 18, 18);
                    g.fillRect(x + 20, y - 20, 18,18 );
                    g.fillRect(x, y - 20, 18, 18);
                    y += 20;gf_y++;
                    g.fillRect(x, y, 18, 18);
                    g.fillRect(x + 20, y, 18, 18);
                    g.fillRect(x + 20, y - 20, 18,18 );
                    g.fillRect(x, y - 20, 18, 18);
                    g.setXORMode(Color.red);
                    t.sleep(500);
                    
                    

            } catch (InterruptedException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            }
        }


    }

    @Override
    public void keyTyped(KeyEvent e) {
        System.out.println(e.getKeyChar() + " pressed");
    }

    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println(e.getKeyChar() + " pressed");
        int taste = e.getKeyCode();
        if (taste == KeyEvent.VK_RIGHT) {
            x += 10;
        }
        if (taste == KeyEvent.VK_LEFT) {
            x -= 10;
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
         System.out.println(e.getKeyChar() + " pressed");
    }
}
```


----------



## Marco13 (16. Mai 2012)

Chaotisch... versuch's mal ohne GUI-Builder, das dürfte für den Anfang besser sein.

Für die Key-Sachen: Man muss sich genau überlegen, zu welcher Component man den KeyListener hinzufügt. Vielleicht mal How to Use Key Bindings (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features) in Erwägung ziehen. 

[WR]getGraphics auf Components aufrufen ist praktisch immer falsch!!![/WR]

Schau mal unter Malen in Swing Teil 1: der grundlegende Mechanismus ? Byte-Welt Wiki


----------



## DerMeister2010 (16. Mai 2012)

die getGraphics Methode brauch ich damit man auf dem Panel zeichnen kann.

wieso sollte ich den GUI-Builder weglassen alles dynamisch zu erzeugen ist auch nicht die Lösung


----------



## DerMeister2010 (16. Mai 2012)

Habe das Problem gefunden ein kleiner aber wichtiger Fehler der sehr oft passiert Den Focus hat nicht die GUI sonder der Button start was dazu führt das der KEyListener nicht funktioniert.


----------



## Marco13 (16. Mai 2012)

Ja. Das löst aber nicht das Problem... Button auf nicht-Focusable setzen? Einen FocusListener dranhängen, der den Focus zurück zum Frame zieht...? 

getGraphics auf Components braucht man NICHT. Lies' dir den Link durch. Wenn du später einen Thread aufmachst, weil es zu "unerklärlichen" Zeichenfehlern kommt, wirst du wieder das gleiche hören.


----------

