The reason is that background
is a rather large image, and the g2d
is performing a scale and a rotate every time. If you enabledEnabling OpenGL via -Dsun.java2d.opengl=True
as suggested here might help, but I haven't been able to enable it on my machine.
new Thread(() -> {
while(true) {
if (background == null) continue;
// A new BufferedImage to avoid concurrency issues; in this way,
// the reference to this.drawnBackground is always a valid image
// to be drawn. If we reassign this.drawnBackground = drawnBackground
// while paintComponent() is running, that's fine, as it will simply
// draw the old image.
// It's also important to note that assignment to references
// is an atomic operation, so we don't have to declare the field
// as volatile
BufferedImage drawnBackground = new BufferedImage(background.getWidth(), background.getHeight(), background.getType());
Graphics2D g2d = (Graphics2D) drawnBackground.getGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, background.getWidth(), background.getHeight());
float xscale = (float) SCREENWIDTH / WIDTH;
float yscale = (float) SCREENHEIGHT / HEIGHT;
g2d.scale(xscale, yscale);
g2d.rotate(Math.toRadians(45), WIDTH / 2, HEIGHT / 2);
g2d.drawImage(background, 0, 0, this);
this.drawnBackground = drawnBackground;
}
}).start();