Sign in to follow this  
tufflax

[java] BufferStrategy problem, graphics disappear

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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();
}
}

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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);

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this