I am attempting to make a pong game but every time I try to launch it to test the buffer strategy, it immediately closes. I tried resolving this by adding a start and stop synchronized void, but it did not seem to work. Normally this kind of thing can be easy to fixed but I am baffled.
package pong;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
JFrame frame; //game window stuff
public final int WIDTH = 400;
public final int HEIGHT = WIDTH / 16 * 9;
public final Dimension gameSize = new Dimension(WIDTH, HEIGHT);
public final String TITLE = "Pong InDev";
BufferedImage Image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
static boolean gameRunning = false; //Is game running?
public void run() {
while (gameRunning) {
tick();
render();
}
}
//attempted to fix problem
public synchronized void start1() {
gameRunning = true;
new Thread(this).start();
System.exit(0);
//End start method
}
public static synchronized void stop() {
gameRunning = false;
//End stop method
}
public Game() {
frame = new JFrame();
setPreferredSize(gameSize);
setMinimumSize(gameSize);
setMaximumSize(gameSize);
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
frame.setTitle(TITLE);
frame.setLocationRelativeTo(null);
frame.setLayout(new BorderLayout());
}
public void tick() {
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(Image, 0, 0, getWidth(), getHeight(), null);
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.dispose();
bs.show();
}
public static void main(String[] args) {
Game game = new Game();
game.start1();
}
}
System.exit(0) at the end of the start method looks like the culprit. Try removing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With