我正在尝试使用 Java2D 制作一个简单的游戏以获得最大的兼容性。它在 Mac OS X Yosemite 上的 Java 8 下运行良好,但是当我在 Windows 7 下尝试相同的代码时,它就没有那么流畅了。当 JFrame 被调整大小时,画布会闪烁,这真的很难看。
我的应用程序使用带有 BufferStrategy 的 AWT Canvas 并且像这样工作。当环境中有东西移动时,另一个线程调用重绘。但是对于窗口大小调整处理,我的策略如下:
public class TestCanvas
{
private static final Color[] colors = new Color[]{Color.black, Color.darkGray, Color.gray, Color.lightGray, Color.blue.darker().darker(), Color.blue, Color.blue.brighter().brighter(), Color.white};
public static void main(String[] args)
{
JFrame frame = new JFrame("Test Canvas");
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BorderLayout());
Canvas canvas = new Canvas()
{
@Override
public void paint(Graphics g)
{
BufferStrategy bufferStrategy = getBufferStrategy();
g = bufferStrategy.getDrawGraphics();
paint100Circles(g);
g.dispose();
bufferStrategy.show();
}
@Override
public void update(Graphics g)
{
paint(g);
}
@Override
public void repaint()
{
paint(null);
}
};
contentPane.add(canvas, BorderLayout.CENTER);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(1000, 1000);
frame.setVisible(true);
canvas.createBufferStrategy(2);
}
public static void paint100Circles(Graphics g)
{
Random random = new Random(0);
for (int i = 0; i < 100; i++)
{
int x = Math.abs(random.nextInt()) % 1000;
int y = Math.abs(random.nextInt()) % 1000 + (Math.abs(random.nextInt() % 1000) / 25);
int size = 50 + Math.abs(random.nextInt()) % 50;
g.setColor(colors[Math.abs(random.nextInt()) % colors.length]);
g.fillOval(x, y, size, size);
}
}
}
也许我没有以正确的方式使用 BufferStrategy?