The drawImage(image, x, y, null);
method used on a Graphics
object in a JPanel
class is taking a long time to complete and making a game run at low FPS, particularly on MacBook Pros it's been tested on - Linux machines appear to run it very well. The time it takes is greatly affected by the size of the image. A number of potential fixes I found online haven't helped, for example:
Graphics.drawImage() in Java is EXTREMELY slow on some computers yet much faster on others and also a suggestion to use different versions of Java didn't make much difference at all - I tried both Java 6 and 8, as it was suggested this is sometimes due to Java 7+ versions.
After hours of searching I decided to try creating a completely new project which implemented the very basics of running this method in a loop, and below is the code - in case I'm doing something stupid in it!
The Class that sets up the JFrame:
import javax.swing.JFrame;
public class Main {
public static void main(String args[]) {
JFrame f = new JFrame("Carnival Carnage");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new TPanel());
f.pack();
f.setVisible(true);
}
}
The Class that extends JPanel:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class TPanel extends JPanel implements Runnable {
private Graphics g;
private BufferedImage image;
private Thread thread;
private int width = 1600, height = 900;
public TPanel() {
super();
setPreferredSize(new Dimension(width,height));
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
setFocusable(true);
requestFocus();
}
private void draw() {
g = getGraphics();
long start = System.nanoTime();
g.drawImage(image, 0, 0, null);
System.out.println(System.nanoTime() - start);
}
public void run() {
while(true) {
draw();
}
}
public void addNotify(){
super.addNotify();
if(thread == null) {
thread = new Thread(this);
thread.start();
}
}
}