I have a Game Loop:
public void startGameThread() {
gameLoop();
gameThread = new Thread(this);
gameThread.start();
}
public void gameLoop() {
frame++;
if (System.currentTimeMillis() - lastCheck >= 1000) {
lastCheck = System.currentTimeMillis();
System.out.println("FPS " + frame);
frame = 0;
}
}
@Override
public void run() {
double timePerFrame = 1000000000.0/FPS;
long lastFrame = System.nanoTime();
long now = System.nanoTime();
while (true) {
now = System.nanoTime();
if (System.nanoTime() - lastFrame >= timePerFrame) {
repaint();
update();
gameLoop();
lastFrame = now;
}
}
}
and Main Class with GUI:
package MainPackage;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MainClass implements ActionListener {
public static boolean Clicked = false;
public static void main(String[] args) {
PanelClass pClass = new PanelClass();
JButton start = new JButton("START");
start.setSize(120, 50);
start.setFocusable(false);
start.setLocation(630, 200);
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == start) {
pClass.startGameThread();
Clicked = true;
start.setVisible(false);
}
}
});
start.setVisible(true);
JFrame frame = new JFrame("Tanks");
frame.setSize(1600, 913);
frame.setLayout(null);
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.add(start);
frame.add(pClass);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
}
}
After launching my application, GUI is "blinking". I think that's because of the Game loop. But how to fix it? Any help is really appreciated!
I was expecting to get the usual behavior of the GUI. Ask me to add more details; code, if needed.
Typing this, because stackoverflow need more "details". That's probably stupid, but I don't know what details to add.