Capturing action of certain buttons in a JFrame

1

I created a JFrame that, when clicking the keyboard buttons: up, down, left and right, a certain action should take place (a Joption in the case).

For this I am using a KeyListener , but unfortunately I click on certain buttons and nothing happens.

package projeto;

import java.awt.event.KeyEvent;

import javax.swing.JOptionPane;

public class teste extends javax.swing.JFrame {

    public teste() {
        initComponents();
        setExtendedState(MAXIMIZED_BOTH);
    }

    private void initComponents() {
        cima = new javax.swing.JLabel();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Jogo do Monstro");
        setPreferredSize(new java.awt.Dimension(550, 700));
        getContentPane().setLayout(null);

        cima.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {

                if (evt.getKeyCode() == KeyEvent.VK_LEFT) {
                    JOptionPane.showMessageDialog(null, "esquerda");
                } else if (evt.getKeyCode() == KeyEvent.VK_RIGHT) {
                    JOptionPane.showMessageDialog(null, "direita");
                } else if (evt.getKeyCode() == KeyEvent.VK_UP) {
                    JOptionPane.showMessageDialog(null, "cima");
                } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
                    JOptionPane.showMessageDialog(null, "baixo");
                }
            }
        });
    }

    public static void main(String args[]) {

        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(jogoDoMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(jogoDoMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(jogoDoMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(jogoDoMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new teste().setVisible(true);
            }
        });
    }

    private javax.swing.JLabel cima;}
    
asked by anonymous 20.06.2017 / 00:46

1 answer

2

If you expect the action to occur on the screen, it should be applied to JFrame and not to the component. As it stands, actions will only occur when the component is in focus, in this case the JLabel .

import java.awt.event.KeyEvent;

import javax.swing.JOptionPane;

public class TecladoEvento extends javax.swing.JFrame {

    public TecladoEvento() {
        initComponents();
        setExtendedState(MAXIMIZED_BOTH);
    }

    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Jogo do Monstro");
        setPreferredSize(new java.awt.Dimension(550, 700));
        getContentPane().setLayout(null);

        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {

                if (evt.getKeyCode() == KeyEvent.VK_LEFT) {
                    JOptionPane.showMessageDialog(null, "esquerda");
                } else if (evt.getKeyCode() == KeyEvent.VK_RIGHT) {
                    JOptionPane.showMessageDialog(null, "direita");
                } else if (evt.getKeyCode() == KeyEvent.VK_UP) {
                    JOptionPane.showMessageDialog(null, "cima");
                } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
                    JOptionPane.showMessageDialog(null, "baixo");
                }
            }
        });
    }

    public static void main(String args[]) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TecladoEvento().setVisible(true);
            }
        });

    }
}

The only change I made was to remove JLabel and apply the direct listener to JFrame , and everything worked normally.

    
20.06.2017 / 01:25