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.
– user28595
@diegofm whatever, in case I’m using a joption, but no action happens
– user77896
@diegofm I just want any action to happen, it’s for an educational purpose
– user77896
Whatever, if the actions should occur in jframe, the action should be applied to it. Try applying directly to jframe.
– user28595
@diegofm and how I would do it?
– user77896
See the answer below.
– user28595
@diegofm Thank you so much! As always helping me and taking my doubts!
– user77896
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
– user28595