问题
At below, its my code to make a renewable graphics shows life game itself.
public paint(Graphics g)
{
g.setClip();//Set
g.setColor(Color.BLACK);
Processing.....
while(true)
{
g.clearRect();//Clear
g.drawLine(); //Draw;
Calling SwingWorking to prepare next statement
}
}
seems it's stupid to do like this way because when running it, the frame keep flashing and laggy.
I try to use Thread.sleep(), but it just slow down the frequency of flash.
So, my problem is how to make it well and avoid flashing. The parts of code that I don't put on are all about data processing for instance variables, if you need it,please notice me, much appreciate for help.
Thanks, @MadProgrammer
Here is what I got, first, the flash is because when program calling repaint() and paint(), it cost too much time to make animation smoothly, in this case is clearRect() and drawLine().
I'll use double buffered to solve it.
Update,
Thanks guys, I read those examples. I just use a frame without any buffer method to show graphics before, what a mistake. I used bufferStrategy to solve it.
回答1:
Not an answer, but a demonstration
it cost too much time to make animation smoothly
To me, this means you don't understand how the API works, you can do some complex animations with Swing if you put your mind to it.
A while ago I created an "animated sequence" engine, which took a series of images and animated them on top of each other
This examples uses 5 separate images/layers (with a paint effect put over the top)
Each layer is given a different "speed" so that they move at different speeds through out the base time of the animation (for example, a speed of 1 will cause the layer to rotate only once over the base duration of the sequence, in this example, 20 seconds)
The original images are all 1024x256, so that an inconsiderate size
Add ontop of that the sequence is playing in transparent window with the addition of an alpha effect (bleeding off at the edges), this is not a simple animation.
The gif is playing at rough 8fps, the actual animation runs at roughly 200fps
(Sorry, the code for this is quite large and makes use of a number of other libraries, like the Timing Framework, so it's impossible to post)
My point is, the problem isn't with the API (Swing/Graphics) alone, but with how you are using it
For more examples you could have a look at:
- Swing animation running extremely slow
- Slow movement using paintComponent method
- Rotating multiple images causing flickering. Java Graphics2D
and most of these examples aren't even trying for any major optimization or other performance technqiues
You should also have a look at Painting in AWT and Swing and Performing Custom Painting for more details about how the painting process works
来源:https://stackoverflow.com/questions/34735361/jframe-flash-when-updating-graphics