如何在java中使用BufferStrategy时避免黑线
问题描述:
遵循2015年11月发布的指南,我已经逐字复制了他的代码,但它仍然不适用于我。有东西被弃用?如何在java中使用BufferStrategy时避免黑线
我有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
一些重要的教程和例子是执行“翻页”的手段,这与常规喷漆系统无关。这为您提供对绘画过程的“主动”控制。每个缓冲区在屏幕上都会更新,并在准备就绪时推送到屏幕上。
这通常不涉及组件自己的绘画系统,其目的是避免它。
这意味着您不应该在JFrame
或canvas.paint
上致电super.paint(g)
。实际上,一般来说,您绝不应手动拨打paint
。
每次你想更新一个缓冲区时,你都需要“准备”它。这通常意味着有一些基本的颜色填充
因此,基于从JavaDoc中的例子,你可以这样做......
// 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
作为因为它提供了更多可重用的解决方案,并且更容易确定尺寸从
'super.paint(g);'将是第一个错误。你应该自己清除缓冲区 – MadProgrammer
让我试着澄清一下。画布是框架的一个孩子,它的位置被框架边框所抵消,通过调用super.paint,您要求框架将自己绘制到图形上,黑色条实际上是通常由窗口装饰覆盖的区域 – MadProgrammer
太棒了!我将super.paint(g)更改为canvas.paint(g),它现在按预期工作。 –