First off all, I know questiones like this has been asked before, but no answers seem to fix my problem.
I am working on a little game, and for some reason java returns an IllegalStateException whenever I try to create a new bufferstrategy. I am adding the game to a JFrame, but the exception is still thrown, here is the code for adding to the JFrame:
JFrame frame;
public Window(int x, int y, int width, int height, String title, boolean focus, Main game) throws IOException {
frame = new JFrame();
frame.setLocation(x, y);
frame.setSize(new Dimension(width, height));
frame.setTitle(title);
frame.add(game);
game.start();
frame.setAutoRequestFocus(focus);
frame.setFocusable(true);
frame.setVisible(true);
}
And here is the code for creating the window (located in the Main class):
window = new Window(x, y, WIDTH, HEIGHT, "Title", true, this);
I assume createBufferStrategy() is called on frame from game.start().
The IllegalStateException may happen because the JFrame doesn't really exist in the computer (or something like that) until it has been assigned resources from outside the JVM.
When I myself tried to createBufferStrategy(), the error said that "Component must have a valid peer". Peers, apparently, are example versions of graphical components that the OS or graphics manager uses as an archetype for drawing your custom components.
I guess that, until your JFrame is assigned its peer in the OS, it doesn't have all the information it needs to make a BufferStrategy--the size of the JFrame may be listed internally as 0 by 0, perhaps, and it won't be updated to width by height until you tell the JVM to make the Frame showable or "valid". You need to do this before calling game.start().
frame.setVisible(true) will show the frame, and apparently assigns peers as necessary. You can call game.start() afterwards.
If you want to call createBufferStrategy() on an invisible JFrame, try frame.pack(), which validates every component in the frame without showing it. Note: it also compress the frame to fit its components--if you haven't added anything, or haven't called setMinimumSize() yet, the JFrame will shrink.