Okay, I understand your need for an SSCCE, so I created (my first) one.
I managed to replicate the problem with under 200 lines of code. On my system this demo compiled and ran perfectly (only the flickering was still there of course). I stripped everything that had nothing to do with it. So basically we have two source files now: the screen manager and the game manager.
The screen manager: http://pastebin.com/WeKpxEXW
The game manager: http://pastebin.com/p3C5m8UN
You can compile this code with this make file (I use a ported version of Linux' make for Windows): CC = javac BASE = nl/jorikoolstra/jLevel CLASS_FILES = classes/$(BASE)/Game/GameMain.class classes/$(BASE)/Graphics/ScreenManager.class
jLevel: $(CLASS_FILES)
@echo Done.
classes/%.class : src/%.java
@echo Compiling src/$*.java to $@ [command: $(CC) src/$*.java ] ...
@$(CC) -Xlint:unchecked -d classes -classpath src src/$*.java
Where the source files are placed in the /src
directory and the classes in the /classes
directory.
After compilation to byte-code the game can be started using the following .bat file:
@set STARUP_CLASS=nl.jorikoolstra.jLevel.Game.GameMain
@set ARGUMENTS=1280 1024 32
@java -cp classes;resources %STARUP_CLASS% %ARGUMENTS%
Note that the ARGUMENT
variable depends on your own screen settings and that you have to change it so that the game is displayed in the right resolution for your screen.
I see why it is flickering ----
BufferStrategy
is doing a separate painting job from the Component's paint()
method and they seem to use different Graphics
objects and they are refreshing at a different rate --
when paint()
is invoked before show()
, it's fine. But
when paint()
is invoked after show()
, it will repaint the component to its initial blank look -- so flashing happens.
It's very easy to eliminate the flickering: override paint()
method of your JFrame
(GameMain
) as you don't need it to do anything (BufferStrategy
can give you more precise control on painting stuffs):
@Override
public void paint (Graphics g) {}
That's all. (I have tested it and it works fine, hope this may help :))
Instead of overriding paint()
method, a better way is to call setIgnoreRepaint(true)
for your JFrame
(GameMain
) -- this method is just designed for such purposes! USE IT!
private GameMain(String ... args)
{
setIgnoreRepaint(true);
.....
}