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;}