keyPressed is not working after adding ActionListener to JButton
Posted
by
Yehonatan
on Game Development
See other posts from Game Development
or by Yehonatan
Published on 2012-11-23T09:21:47Z
Indexed on
2012/11/23
11:17 UTC
Read the original article
Hit count: 265
java
I have a serious problem while trying to build a menu for my game. I've added two JButton to a main JPanel and added an ActionListener for each of them. The main JPanel also contains the game JPanel which have the keyPressed method inside keyController.
That's how it looks -
Main ->
JPanel ->
JButton, JButton,
JPanel which contains the game and keyPressed function inside KeyController class which worked fine before I added the ActionListener for JButton.
For some reason after I added an ActionListener for each of the button, the game JPanel is not getting any keyPreseed events nor KeyRealesed.
Does anyone know the solution for my situation?
Thank you very much!
Main window -
Scanner in = new Scanner(System.in);
JFrame f = new JFrame("Square V.S Circles");
f.setUndecorated(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.add(new JPanelHandler());
f.pack();
f.setVisible(true);
f.setLocationRelativeTo(null);
JPanelHandler(main JPanel) -
super.setFocusable(true);
JButton mybutton = new JButton("Quit");
JButton sayhi = new JButton("Say hi");
sayhi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("Hi");
}
});
mybutton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
add(mybutton);
add(sayhi);
add(new Board(2));
Board KeyController(The code inside is working so it's unnecessary to put it here) -
private class KeyController extends KeyAdapter {
public KeyController()
{
..Code
}
@Override
public void keyPressed(KeyEvent e) {
...Code
}
@Override
public void keyReleased(KeyEvent e){
...Code
}
}
© Game Development or respective owner