Last active
October 12, 2020 19:59
-
-
Save jmhertlein/9514d5729fe7be9cbe79 to your computer and use it in GitHub Desktop.
JFrame boilerplate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.Color; | |
import java.awt.Graphics; | |
import javax.swing.JFrame; | |
import javax.swing.SwingWorker; | |
public class MuhJFrame extends JFrame { | |
private SwingWorker gameLooper; | |
private boolean stop; | |
private int seconds; | |
public MuhJFrame() { | |
setSize(800, 600); | |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
seconds = 0; | |
stop = false; | |
gameLooper = new SwingWorker() { | |
@Override | |
protected Object doInBackground() throws Exception { | |
while(!stop) { | |
update(); | |
repaint(); | |
Thread.sleep(1000); //lazy 1 FPS & 1 update per second | |
} | |
return null; | |
} | |
}; | |
gameLooper.execute(); | |
} | |
@Override | |
public void paint(Graphics grphcs) { | |
super.paint(grphcs); //do not remove | |
getGraphics().setColor(Color.BLACK); | |
grphcs.drawString("second: " + seconds, 200, 200); | |
} | |
public void update() { //DON'T update the UI in this method. Game logic ONLY! | |
seconds++; | |
} | |
public static void main(String[] args) { | |
MuhJFrame f = new MuhJFrame(); | |
f.setVisible(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment