Hello, i just started to game programing with java, before that i was using c# Xna.I wrote my engine,and it is working fine.But i didn’t use a canvas.You can see my game engine below.I’m wondering should i use canvas to draw (if so why?) or not?
And i saw nobody preferred using timers to a while loop and my fps should be fixed 60 but it is more than 60 so am i doing something wrong ?
package kutuyatopat;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Engine extends JFrame {
int frameRate = 0;
int frameCounter = 0;
long StartTime = System.currentTimeMillis();
long EndTime;
long ElapsedTime = 0;
JPanel panel;
JLabel label;
Vector<IComponent> Components;
GraphicsConfiguration gc;
public Engine(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
this.setLocationRelativeTo(null);
panel = new JPanel();
this.add(panel);
label = new JLabel();
panel.add(label);
Components = new Vector<IComponent>();
gc = GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration();
}
protected void Initialize(){
Timer t = new Timer();
TimerTask tt = new TimerTask(){
@Override
public void run() {
EndTime = System.currentTimeMillis();
long elapsedTime = EndTime - StartTime;
GameLoop(elapsedTime);
StartTime = System.currentTimeMillis();
}
};
t.scheduleAtFixedRate(tt, 10, 1000 / 60);
}
void GameLoop(long elapsedTime){
Update(elapsedTime);
Draw();
}
public void Update(long elapsedTime){
ElapsedTime += elapsedTime;
if(ElapsedTime > 1000){
ElapsedTime -= 1000;
frameRate = frameCounter;
frameCounter = 0;
}
for(IComponent c : Components){
c.Update(ElapsedTime);
}
}
public void Draw(){
frameCounter++;
String fps = "Fps: " + frameRate;
BufferedImage i = gc.createCompatibleImage(this.getWidth(), this.getHeight(),Transparency.BITMASK);
Graphics2D g2 = i.createGraphics();
for(IComponent c : Components){
c.Draw(g2);
}
g2.setColor(Color.white);
g2.drawString(fps, 30, 40);
g2.dispose();
ImageIcon ic = new ImageIcon(i);
label.setIcon(ic);
}
}