Skip to main content
gamedev.net
🔒 Locked

[java] BufferStrategy problem, graphics disappear

Started by tufflax 5 replies 1.7k views
Original Post
tufflax
tufflax
Hey! I know how to use BufferStrategy, but, when i .show() my graphics, they instantly disappear (one can see them a very, very short period of time). Sometimes the graphics stay in place but when i Alt+Tab away and come back, they are gone. Does anyone know the solution to this problem?
Vyper_uk
Vyper_uk
It would help if you posted your code
tufflax
tufflax
Alright, here it is.

class Airhockey {	JFrame frame;	Graphics2D gfx;	BufferStrategy bs;	public Airhockey() {		frame = new JFrame("Airhockey");			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		frame.setSize(500, 600);		frame.setVisible(true);		frame.createBufferStrategy(2);		bs = frame.getBufferStrategy();						test();	}			private void test() {		gfx = (Graphics2D) bs.getDrawGraphics();		gfx.setColor(Color.black);		gfx.fillRect(0, 0, 100, 100);		bs.show();	}}
Vyper_uk
Vyper_uk
Ok, I could just post a fix for your code but I think it would be better if you went here and worked through the tutorial. It isn't perfect but it will get you started and will probably answer a lot of other questions you will come across
tufflax
tufflax
Thank you.

But, the tutorial doesn't answer my particular question as far as I can see. It just tells the reader to do what I have done. And I do see some graphics too when I'm using my code, so it works. It's just that they disappear sometimes.

I have noticed, however, that it works when drawing stuff repeatedly in a loop. That's what I want to do in my game, of course, so I guess it isn't a problem anymore.
Vyper_uk
Vyper_uk
Yes, thats what you were meant to learn :). What is actually happening in that tutorial is that the paint() method gets called automatically every time the component is scheduled for repainting. However in your code the box was being painted once, but then there was no way for java to know that it should paint that box every time.

Rather than just using a loop you may also want to look into running your loop within a thread. Otherwise when you start to collect user input you could get problems with the input thread being starved by the loop.
5MinuteGaming
5MinuteGaming
If you want to make the frame not paint over what you've painted then you there is a method in java.awt.Component called setIgnoreRepaint(boolean) but unfortunately if you set this you will have to handle repainting the Component yourself but it's very usefull for eliminating some problems

so

frame.setIgnoreRepaint(true);

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.