So here it is:
package org.dane.test;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class TestLoop extends JApplet implements Runnable {
private Thread thread;
private boolean active;
private BufferedImage image;
// Other Variables
int operationPos = 0;
int ratio = 256;
int delay = 1;
int count = 0;
int interruptionCount = 0;
int interval = 1000 / 50; // 50 is the goal fps.
int fps = 0;
long[] operationTime = new long[10];
long currentTime;
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.setLayout(new BorderLayout());
frame.setResizable(false);
frame.add(new TestLoop(256, 256), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public TestLoop(int width, int height) {
this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
this.setPreferredSize(new Dimension(width, height));
this.thread = new Thread(this);
this.thread.start();
}
@Override
public void run() {
this.active = true;
for (int i = 0; i < operationTime.length; i++) {
operationTime[i] = System.currentTimeMillis();
}
while (this.active) {
ratio = 300;
delay = 1;
currentTime = System.currentTimeMillis();
// What's this doing?
if (currentTime > operationTime[operationPos]) {
ratio = (int) (2560 * (interval / (currentTime - operationTime[operationPos])));
}
if (ratio < 25) {
ratio = 25;
}
if (ratio > 256) {
ratio = 256;
delay = (int) (interval - (currentTime - operationTime[operationPos]) / 10L);
}
if (delay > interval) {
delay = interval;
}
operationTime[operationPos] = currentTime;
operationPos = (operationPos + 1) % 10;
// ???
if (delay > 1) {
for (int i = 0; i < 10; i++) {
if (operationTime[i] != 0L) {
operationTime[i] += delay;
}
}
}
if (delay < 1) {
delay = 1;
}
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
interruptionCount++;
}
for (; count < 256; count += ratio) {
// TODO: logic();
}
fps = (1000 * ratio) / (interval * 256);
this.repaint();
}
}
@Override
public void paint(Graphics graphics) {
Graphics g = this.image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.BLACK);
int x = 4;
int y = 16;
for (int i = 0; i < 10; i++) {
int optim = (operationPos - i + 20) % 10;
g.drawString("optim" + optim + ": " + operationTime[optim], x, y);
y += 16;
}
g.drawString("fps: " + fps + " ratio: " + ratio + " count: " + count, x, y);
y += 16;
g.drawString("delay: " + delay + " interval: " + interval, x, y);
y += 16;
g.drawString("interruptions: " + interruptionCount + " opos: " + operationPos, x, y);
graphics.drawImage(this.image, 0, 0, null);
graphics.dispose();
}
private static final long serialVersionUID = 3633102351301301398L;
}