遵循2015年11月发布的指南。目前,我已逐字复制了他的代码,但它仍然对我不起作用。是否已弃用某些东西?
我有3个缓冲区(分别称为1,2和3)。当在屏幕上绘制2和3时,它们在屏幕的顶部和左侧都有黑线。相同的代码可以在两个缓冲区中正常工作。
错误片段: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();
}
}
最佳答案
您需要阅读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
作为基础,因为它提供了更可重用的解决方案,并且更容易从中确定尺寸