When click MenuItem NewGame. It works, but press F2 it doesn't
mntmNewGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int n = JOptionPane.showConfirmDialog(contentPane,"Do you want to play new game ?", "Message!", JOptionPane.OK_CANCEL_OPTION);
}
});
mntmNewGame.addKeyListener(new KeyAdapter() {
public void keyListener(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_F2)
{
int n = JOptionPane.showConfirmDialog(contentPane,"Do you want to play new game ?", "Message!", JOptionPane.OK_CANCEL_OPTION);
}
}
});
This is why you should always use @Override
when overriding methods... KeyAdapter
doesn't have a keyListener
method - it has keyPressed
, keyReleased
and keyTyped
. For example, you might want:
mntmNewGame.addKeyListener(new KeyAdapter() {
@Override public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_F2) {
int n = JOptionPane.showConfirmDialog(
contentPane,
"Do you want to play new game ?",
"Message!",
JOptionPane.OK_CANCEL_OPTION);
// Use n, presumably...
}
}
});
With the @Override
annotation, if you make a typo, the compiler will spot that you're trying to override something, but not actually doing so - so you get a compile-time error, rather than just a method that's never called.
See more on this question at Stackoverflow