I have been trying to convert one of my games into an Applet but since it is my first time using an Applet I ran into a problem. Basically whenever I open the game the screen start blinking. I'm pretty sure that it is due to not having a BufferStrategy but whenever I try to create one like "BufferStrategy bg = this.getBufferStrategy()" it doesn't work. Can someone help?
package main;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JApplet;
import Handling.Handler;
import Other.HUD;
import Other.KeyInput;
public class Game extends JApplet implements Runnable{
private static final long serialVersionUID = 9021342660060318393L;
public static final int WIDTH = 640;
public static final int HEIGHT = WIDTH / 12 * 9;
private Thread thread;
private boolean running = false;
private Handler handler;
private HUD hud;
private Spawner spawner;
private Menu menu;
public enum STATE{
Menu(),
Help(),
Settings(),
DeathScreen(),
Game();
};
public enum DIFFICULTY{
Easy(),
Mediuм(),
Hard();
};
public STATE GameState = STATE.Menu;
public DIFFICULTY difficulty = DIFFICULTY.Easy;
private void tick(){
handler.tick();
if(GameState == STATE.Game){
hud.tick();
spawner.tick();
}else if(GameState == STATE.Menu){
menu.tick();
}
}
public void paint(Graphics g){
//DRAW HERE
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
handler.paint(g);
if(GameState == STATE.Game){
hud.paint(g);
}else if(GameState == STATE.Menu || GameState == STATE.Help || GameState == STATE.Settings || GameState == STATE.DeathScreen){
menu.paint(g);
}
//STOP DRAWING
g.dispose();
}
public void init(){
setSize(WIDTH,HEIGHT);
handler = new Handler();
menu = new Menu(this, handler);
this.requestFocusInWindow(true);
this.setFocusable(true);
this.addKeyListener(new KeyInput(handler));
this.addMouseListener(menu);
hud = new HUD();
spawner = new Spawner(handler, hud, this);
}
public void start(){
thread = new Thread(this);
thread.start();
running = true;
}
public void destroy(){}
public void stop(){
try {
System.exit(1);
thread.join();
running = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
this.requestFocus();
long LastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running){
long now = System.nanoTime();
delta += (now - LastTime) / ns;
LastTime = now;
while(delta >= 1){
tick();
repaint();
delta--;
}
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println("FPS: " + frames);
frames = 0;
}
try {
thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stop();
}
}