Below is a simplified version of my code. The menu panel just has a start button and the game panel is just a black screen with a square that's supposed to move when the arrow keys are pressed. So when I click the button in the menu panel to start the game, the graphics load up fine, but the key listener doesn't work at all. This seems to only be a problem when there are multiple panels involved, or when I switch between them. I'm a complete beginner, so any advice would be really helpful.
Main class
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
MyFrame frame= new MyFrame();
frame.setSize(1000,1000);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
MyFrame Class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFrame extends JFrame implements ActionListener{
CardLayout card;
JButton b1;
Container c;
MyPanel game;
JPanel menu;
public MyFrame(){
c=getContentPane();
card=new CardLayout();
c.setLayout(card);
game = new MyPanel();
menu = new JPanel();
b1=new JButton("Start");
b1.addActionListener(this);
c.add("p", menu);
menu.add("a",b1);
c.add("d", game);
}
public void actionPerformed(ActionEvent e) {
card.show(c, "d");
}
}
MyPanel class
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.*;
public class MyPanel extends JPanel implements ActionListener, MouseListener, MouseMotionListener, KeyListener{
Timer myTimer;
int x = 0;
int y = 0;
int xVel, yVel;
public MyPanel() {
myTimer = new Timer(50, this);
myTimer.start();
this.addKeyListener(this);
this.setFocusable(true);
this.requestFocusInWindow();
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
public void startTimer() {
myTimer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.BLACK);
g.setColor(Color.CYAN);
g.drawRect(x, y, 100, 100);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==myTimer) {
repaint();
x += xVel;
y += yVel;
}
}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key== KeyEvent.VK_UP) {
up();
}
if(key== KeyEvent.VK_DOWN) {
down();
}
if(key== KeyEvent.VK_RIGHT) {
right();
}
if(key== KeyEvent.VK_LEFT) {
left();
}
}
public void keyReleased(KeyEvent e) {
xVel = 0;
yVel = 0;
}
public void up() {
xVel = 0;
yVel = -5;
}
public void down() {
xVel = 0;
yVel = 5;
}
public void right() {
xVel = 5;
yVel = 0;
}
public void left() {
xVel = -5;
yVel = 0;
}
}