我根据我在stackoverflow上找到的很多例子把这段代码放在一起。当我运行程序时,整个屏幕都会激烈地闪烁。我确信有一些简单的东西我可以忽略,但到目前为止一直无法找到解决方案。我已经调试了几个小时,主要是借助在线论坛阅读,所以我觉得是时候向观众询问了。
public class Screen扩展了JComponent {
@Override
public Dimension getPreferredSize(){
Dimension tempDimension = Toolkit.getDefaultToolkit().getScreenSize();
return tempDimension;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D)bufferStrategy.getDrawGraphics();
g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); //sprites overlap instead of overwrite
if(game==null){
drawSplash(g2D);
}else{
drawBoard(g2D);
}
g2D.dispose();
bufferStrategy.show();
}
}
如果需要任何其他代码,我可以提供。谢谢你的帮助,stackoverflow!
答案 0 :(得分:0)
要获得您获得的结果,您要么拥有另一个类,该类从Canvas
延伸,要么使用顶级容器中的BufferStrategy
。在任何一种情况下,两者都必须在屏幕上可见。
基本上,他们互相争斗,因为他们是两种不同的绘画算法。 Swing是一种被动绘制算法,可根据需要绘制更新,BufferStrategy
使用主动算法,要求您根据需要安排对缓冲区的更新。
两者都使用双缓冲算法。
所以,你应该选择一个......
public class Screen extends JComponent {
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g.create();
g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); //sprites overlap instead of overwrite
if (game == null) {
drawSplash(g2D);
} else {
drawBoard(g2D);
}
g2D.dispose();
}
}
或类似......
public void gameEngine(BufferStrategy strategy) {
// 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
// to make sure the strategy is validated
Graphics2D g2D = (Graphics2D) strategy.getDrawGraphics();
// Render to graphics
g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); //sprites overlap instead of overwrite
if (game == null) {
drawSplash(g2D);
} else {
drawBoard(g2D);
}
// Dispose the graphics
g2D.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());
}
}
这几乎是从JavaDocs for BufferStrategy
BTW,这......
@Override
public Dimension getPreferredSize(){
Dimension tempDimension = Toolkit.getDefaultToolkit().getScreenSize();
return tempDimension;
}
是一个非常糟糕的设计,你正在对可能无法满足现实的组件状态做出假设。您应该允许窗口决定它最终想要的大小,这可以通过使用setExtendedState
并传递JFrame.MAXIMIZED_BOTH
来实现,这将考虑其他操作系统元素,如任务栏或停靠