Reputation: 971
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();
}
}
}
Upvotes: 0
Views: 321
Reputation: 324098
You have an infinite loop that will continue repainting the image.
You should NOT be using getGraphics() and doing painting with that Graphics object because the painting is not permanent.
Custom painting is done by overriding the paintComponent()
method of JPanel and then you use the Graphics object passed to that method.
Read the section from the Swing tutorial on Custom Painting for more information and examples.
To schedule the animation you can use a Swing Timer.
Upvotes: 1