I am trying to make a menu class for a small game I'm making, and it all works fine, except now, the KeyListener
does not work at all, I tried applying it to JFrame
and JPanel
, but nothing is working...
Here is my MainClass
:
package bombermangame;
import javax.swing.JFrame;
public class MainClass {
public static int WIDTH = 870, HEIGHT = 800;
public static JFrame frame = new JFrame();
public static Menu menu = new Menu();
public static void main(String[] args) {
frame.setContentPane(menu);
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("BomberMan V0.3");
frame.setSize(WIDTH, HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
`
And here is my Menu
class:
package bombermangame;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Menu extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton startButton = new JButton("Play");
private int x = 0, y = 500;
private boolean down = false;
private boolean up = true;
private Timer timer = new Timer();
public Menu() {
setBackground(Color.blue);
startButton = new JButton("Start");
startButton.setBounds(0,0, 100, 40);
startButton.setPreferredSize(new Dimension(100, 40));
startButton.addActionListener(this);
startButton.setFocusPainted(true);
add(startButton);
}
public void actionPerformed(ActionEvent ae) {
Object a = ae.getSource();
Game game = new Game();
Listener keys = new Listener();
if (a == startButton) {
timer.cancel();
MainClass.frame.remove(MainClass.menu);
MainClass.frame.setContentPane(game);
MainClass.frame.addKeyListener(keys);
game.addKeyListener(keys);
game.setBackground(Color.BLACK);
game.setDoubleBuffered(true);
game.setBounds(0, 0, WIDTH, HEIGHT);
Game.running = true;
}
}
}