Reputation: 5
Sorry for the messed up title 'cause I don't really know what title I should use xD Anyways here's the problem. So I got this simple game that starts with a Jframe that contains a single button which is if pressed, changes the contents of it to the content of another class that contains the game itself. The problem is that the controls doesn't work right away. (controls, I mean when you press space, the character in the game must shoot but he doesn't because of this problem) It doesn't work right away I mean you need to switch to another window and then go back to your game window and the controls will work. Is there anything I can do with my game so that I won't need to switch windows for the controls to work?
Here's the code of the Jframe:
package rtype;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Rtype extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
public Rtype() {
setSize(1020, 440);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setTitle("PROJECT JAEGER");
setResizable(false);
JButton startButton = new JButton("START GAME");//The JButton name.
add(startButton);//Add the button to the JFrame.
startButton.addActionListener(this);//Reads the action.
setVisible(true);
}
public static void main(String[] args) {
new Rtype();
}
public void actionPerformed(ActionEvent i) {
getContentPane().removeAll();
add(new Board());
System.out.println("The Button Works!");//what the button says when clicked.
revalidate();
setVisible(true);
}
}
the Board in the add(new Board()); is the class of the game.
Upvotes: 0
Views: 273
Reputation: 347194
Since you've not provided the Board
class, I would assume from your description that you are using one or more KeyListener
s.
This is a common problem with KeyListener
. The component it is registered to must not only be focusable, but it must have current focus.
Instead of using KeyListener
, you should be using the Key Bindings API which has mechanisms overcomes these limitations
Upvotes: 1