遵循2015年11月发布的指南。我已经逐字复制了他的代码,但它仍然不适用于我。有什么东西被弃用了吗?
我有3个缓冲区(称为1,2和3)。当2和3被绘制到屏幕时,它们在屏幕的顶部和左侧具有黑线。这个相同的代码适用于两个缓冲区。
Bug素材:https://gfycat.com/gifs/detail/GraveCompetentArmyworm
package field;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.image.BufferStrategy;
public class Main extends JFrame{
private Canvas canvas=new Canvas();
public Main() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(0,0,1000,1000);
setLocationRelativeTo(null);
add(canvas);
setVisible(true);
canvas.createBufferStrategy(3);
BufferStrategy buffert = canvas.getBufferStrategy();
int p=0;
int ap=0;
while(p<1000) {
if (ap==100){
p++;
ap=0;
}
ap++;
buffert=canvas.getBufferStrategy();
Graphics g = buffert.getDrawGraphics();
super.paint(g);
g.setColor(Color.GREEN);
g.fillOval(p+100, 200, 50, 50);
buffert.show();
}
}
// public void paint(Graphics graphics) {
// super.paint(graphics);
// graphics.setColor(Color.RED);
// graphics.fillOval(100, 100, 100, 100);
//
// }
public static void main(String[] args){
new Main();
}
}
答案 0 :(得分:1)
您需要阅读the JavaDocs for BufferStrategy
和Full-Screen Exclusive Mode API,其中包含BufferStrategy
BufferStrategy
是执行“页面翻转”的一种方法,它独立于常规绘画系统。这为您提供了对绘画过程的“主动”控制。每个缓冲区都会在屏幕上更新,并在准备就绪后推送到屏幕上。
这通常不涉及组件自己的绘画系统,目的是避免它。
这意味着您不应该在super.paint(g)
或JFrame
上致电canvas.paint
。事实上,作为一般规则,您不应该手动调用paint
。
每次要更新缓冲区时,都需要“准备”它。这通常意味着用一些基色填充它
因此,基于JavaDocs的示例,您可以执行类似......
的操作// Check the capabilities of the GraphicsConfiguration
...
// Create our component
Window w = new Window(gc);
// Show our window
w.setVisible(true);
// Create a general double-buffering strategy
w.createBufferStrategy(2);
BufferStrategy strategy = w.getBufferStrategy();
// Main loop
while (!done) {
// Prepare for rendering the next frame
// ...
// Render single frame
do {
// The following loop ensures that the contents of the drawing buffer
// are consistent in case the underlying surface was recreated
do {
// Get a new graphics context every time through the loop
// Determine the current width and height of the
// output
int width = ...;
int height = ...l
// to make sure the strategy is validated
Graphics graphics = strategy.getDrawGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
// Render to graphics
// ...
// Dispose the graphics
graphics.dispose();
// Repeat the rendering if the drawing buffer contents
// were restored
} while (strategy.contentsRestored());
// Display the buffer
strategy.show();
// Repeat the rendering if the drawing buffer was lost
} while (strategy.contentsLost());
}
// Dispose the window
w.setVisible(false);
w.dispose();
现在,就个人而言,我更倾向于使用Canvas
作为基础,因为它提供了一个更易于使用的解决方案,并且更容易确定维度