Game lagging horribly

My game is lagging horribly… I’m running it on a timer, and once I get to about 15 enemies on the screen, it lags. Does anyone have any suggestions? Sorry for bad code, I’m a fairly new programmer.

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;

public class GameFrame extends JPanel implements ActionListener {

	Timer mainTimer;
	Player player;

	public static int level = 1;

	static ArrayList<Enemy> enemies = new ArrayList<Enemy>();
	static ArrayList<Missile> missiles = new ArrayList<Missile>();

	Random rand = new Random();

	// starts the game timer and starts the game
	public GameFrame() {
		setFocusable(true);
		player = new Player(150, 450);
		addKeyListener(new KeyAdapt(player));

		mainTimer = new Timer(10, this);
		mainTimer.start();

		startGame();

	}

	// paints the images to the game window
	public void paint(Graphics g) {
		super.paint(g);
		Graphics2D g2d = (Graphics2D) g;

		// draws the background
		ImageIcon bg = new ImageIcon(getClass().getResource("background.png"));
		g2d.drawImage(bg.getImage(), 0, 0, null);

		// draws the stats and upgrade panels
		ImageIcon stats = new ImageIcon(getClass().getResource("stats.png"));
		g2d.drawImage(stats.getImage(), 530, 0, null);

		ImageIcon ug = new ImageIcon(getClass().getResource("upgrades.png"));
		g2d.drawImage(ug.getImage(), 530, 250, null);

		player.draw(g2d);

		for (int i = 0; i < enemies.size(); i++) {
			Enemy tempEnemy = enemies.get(i);
			tempEnemy.draw(g2d);
		}

		for (int i = 0; i < missiles.size(); i++) {
			Missile m = missiles.get(i);
			m.draw(g2d);
		}

		// displays what level you are on, and your points
		g2d.drawString("Level :" + level, 550, 50);
		g2d.drawString("Enemy count: " + enemies.size(), 550, 70);
		g2d.drawString("Health :" + Player.health, 550, 90);
		g2d.drawString("Speed :" + Player.speed, 550, 110);
		g2d.drawString("Missile Count :" + Player.missileCount, 550, 130);
		g2d.drawString("Damage :" + Player.missilePower, 550, 150);

		// displays the upgrades available and how much they cost
		// speed
		g2d.drawString("1: +1 Speed", 535, 320);
		g2d.drawString("" + Player.speed * 10, 620, 320);
		// health
		g2d.drawString("2: " + (Player.healthpool + 5) + " health", 535, 340);
		g2d.drawString("" + Player.healthpool * 10, 620, 340);
		// missileCount
		g2d.drawString("3: +1 missile", 535, 360);
		g2d.drawString("" + Player.missileCount * 3, 620, 360);
		// missilePower
		g2d.drawString("4: +1 Damage", 535, 380);
		g2d.drawString("" + Player.missilePower * 6, 620, 380);
		// points
		g2d.drawString("Points :" + Player.points, 535, 400);
		//instructions
		g2d.drawString("Instructions: press", 535, 410);
		g2d.drawString("the corresponding", 535, 420);
		g2d.drawString("number on the left", 535, 430);
		g2d.drawString("to upgrade.", 535, 440);

	}

	// controls actions, checks if game has ended
	public void actionPerformed(ActionEvent arg0) {
		player.update();

		for (int i = 0; i < enemies.size(); i++) {
			Enemy tempEnemy = enemies.get(i);
			tempEnemy.update();
		}

		for (int i = 0; i < missiles.size(); i++) {
			Missile m = missiles.get(i);
			m.update();
		}

		checkEnd();
		repaint();
		try{
			Thread.sleep(20);
		}catch(InterruptedException ex){}
	}

	// adds enemies
	public void addEnemy(Enemy e) {
		enemies.add(e);
	}

	// removies enemies
	public static void removeEnemy(Enemy e) {
		enemies.remove(e);
	}

	// arraylist to store the number of enemies
	public static ArrayList<Enemy> getEnemyList() {
		return enemies;
	}

	// adds missiles
	public static void addMissile(Missile m) {
		missiles.add(m);
	}

	// removes missiles
	public static void removeMissile(Missile m) {
		missiles.remove(m);
	}

	// arraylist to store the number of missiles
	public static ArrayList<Missile> getMissileList() {
		return missiles;
	}

	// starts the game, loads up enemies
	public void startGame() {
		int enemyOneCount;
		int enemyTwoCount;

		enemyOneCount = level * 2;
		enemyTwoCount = level - 9;
		for (int i = 0; i < enemyOneCount; i++) {
			addEnemy(new EnemyOne(rand.nextInt(400), -10 + -rand.nextInt(600)));
		}
		if (level >= 10) {
			for (int i = 0; i < enemyTwoCount; i++) {
				addEnemy(new EnemyTwo(rand.nextInt(400), -10+ -rand.nextInt(600)));
			}
		}
	}

	// checks if the level is over
	public void checkEnd() {
		if (enemies.size() == 0) {
			if (Player.health > 0) {
				level++;
				enemies.clear();
				missiles.clear();
				startGame();
			} else {
				JOptionPane.showMessageDialog(null,"You lose! You made it to level " + level);
				System.exit(0);
			}
		}
	}
}

You are creating new resources in every frame:

ImageIcon bg = new ImageIcon(getClass().getResource("background.png"));

ImageIcon ug = new ImageIcon(getClass().getResource("upgrades.png"));

I don’t see your Enemy class in here, but if you are doing something similar with them, then that could cause your proposed issues.

Create all your resources before starting your game loop, then just reference those.

Do you have a skype or a website I could upload my project file to for you to look at? I see what you’re saying, but I’m not sure where I should place those resources. I’m looking at it now

  1. Don’t be loading assets every time you need to render something. If possible, use a cache.
  2. Use BufferedImage instead of ImageIcon. ImageIcon is just for that - for icons!
  3. Use a BufferStategy to render, this ensures GPU-page flipping on some hardware.
  4. Convert BufferedImages to device-compatible format before displaying them.

Literally just pull those declarations out of the paint method and make them fields, like you have the Player object. You don’t even need to write any extra code.

Oh, as well. Look up double buffering for Java2D. That’d be helpful.

  1. Instead of using new ImageIcon(blah) every time in paint(), create some BufferedImage fields and reference them in paint().
  2. Load BufferedImages in your constructor with ImageIO.read().
  3. Try and switch to a BufferStategy if you can, this will greatly improve performance.
  4. Use this code to create a device-compatible image:

public static BufferedImage toCompatibleImage(BufferedImage image, boolean override, boolean disposeOld) {
        if (image.getColorModel().equals(gfxConfig.getColorModel()) && !override) {
            return image;
        }
        BufferedImage newImage = gfxConfig.createCompatibleImage(image.getWidth(), image.getHeight(), image.getTransparency());
        Graphics2D g2d = newImage.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();
        if (disposeOld) {
            image.flush();
        }

        return newImage;
    }

Okay, I did that. I’m looking into using BufferedImages now, reading up on it. :slight_smile: Thank you for the help both of you

I would not recommend putting Thread.sleep in your actionPerformed() method. Because you are running on the main thread, all you are doing is slowing down all processes for 20 ms (lag).

Thank you! I put that in there originally to try to solve the issue by putting the thread to sleep, but I forgot to take it out. I appreciate everyone’s help.