Capture action of certain buttons in a Jframe

Asked

Viewed 136 times

1

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

That’s why I’m wearing one 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;}
  • Should button actions occur in jframe? Why are they being applied to a jlabel.

  • @diegofm whatever, in case I’m using a joption, but no action happens

  • @diegofm I just want any action to happen, it’s for an educational purpose

  • Whatever, if the actions should occur in jframe, the action should be applied to it. Try applying directly to jframe.

  • @diegofm and how I would do it?

  • See the answer below.

  • @diegofm Thank you so much! As always helping me and taking my doubts!

  • Sometimes it takes me a while to understand the problem (or I seem to do an interrogation about it), but if you have a little patience, we are there to help. : D

Show 3 more comments

1 answer

2


If you expect the action to occur on the screen, it should be applied to JFrame not the component. As it stands, actions will only occur when the component is in focus, in the case of 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 modification I made was to remove the JLabel and apply the System directly to JFrame, and everything worked normally.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.