Reputation: 1
I am making a game and I have it so when I press a button on a menu I made, it loads the game. Both the game and the menu are JPanel
s. The problem is when I click the button it loads the JPanel but the keyboard input doesn't work. Why might this be happening?
Here is the my code:
public class Menu extends JPanel {
static boolean load = false;
JButton play = new JButton("play");
GamePanel panel = new GamePanel();
public Menu(){
setLayout(new FlowLayout());
add(play);
setVisible(true);
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Runner.panel.setPreferredSize(new Dimension(570,700));
add(Runner.panel,0,0);
//repaint();
validate();
}
});
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
draw(g2d);
}
public void draw(Graphics2D g2d){
g2d.drawImage(getBulletImage(),0,0,null);
}
// gets the image file for the player class
public Image getBulletImage(){
ImageIcon ic = new ImageIcon("Menu.png");
return ic.getImage();
}
}
When the button is clicked in, it adds a JPanel
on top of the current JPanel
.
Upvotes: 0
Views: 38
Reputation: 46841
Read this post JPanel not responding to keylistener that is asked in the same context.
Override paintComponent()
method of JPanel
instead of overriding paint()
method.
Sample code:
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
// your custom painting
}
Override getPreferredSize() method instead of setPreferredSize()
method. Don't set the size of the component and just hand over it to Layout Manager to set the size and position of the components that why it's made for.
Sample code:
@Override
public Dimension getPreferredSize(){
return new Dimension(100,50);
}
Read more Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
Use SwingUtilities.invokeLater()
to make sure that EDT is initialized properly.
Read more
Upvotes: 1
Reputation: 2248
Try adding play.setFocusable(true); and play.requestFocus(); after you have created the new JPanel. This should put the focus in the new panel and allow keyboard input
Upvotes: 0