so I am trying to add a Jlabel to show the time elpased on my program but i dont know where to put it and how to add one. I tried using one of the codes that I found and my program just hanged. Hope you can help me:
here's a gist of my code, I have 2 separate java file for my GUI
public class MyFrame extends JFrame implements Serializable,ActionListener{
Canvas canvas;
CanvasManager manager;
public MyFrame() {
canvas = new Canvas();
canvas.setSize(600,700);
this.add(canvas);
canvas.setBackground(Color.green);
this.pack();
this.setVisible(true);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
manager = new CanvasManager(canvas);
manager.start();
}
this is my canvas where i draw my images:
public class CanvasManager extends Thread implements MouseListener, Serializable{
private final int FRAME_DELAY = 200; // 20ms. implies 50fps (1000/20) = 50
private BufferedImage img;
private boolean toggle = true;
private int width = 600;
private int height = 700;
private Canvas canvas;
private long start;
public CanvasManager(Canvas canvas) {
this.canvas = canvas;
this.canvas.setSize(width, height);
this.canvas.addMouseListener(this);
}
public void run() {
start = System.currentTimeMillis();
canvas.createBufferStrategy(2);
BufferStrategy strategy = canvas.getBufferStrategy();
Graphics g = null;
while (true) {
g = strategy.getDrawGraphics();
paint(g);
strategy.show();
syncFramerate();
}
}
I have a thread for my paint function because my program requires to keep repainting the canvas.
A solution would be to add a Jlabel to the class that extends frame.
JLabel lbl = new JLabel("Text"); // instance variable
this.add(lbl); // this should go in constructor
Then as time passes, you would update the text in the JLabel
lbl.setText("Time");
Then in your game loop you would initiate a Timer/ Swing Timer and change the Text of the JLabel when the time action is fired...
Timer timer = new Timer(1000, new ActionListener() { //Change parameters to your needs.
@Override
public void actionPerformed(ActionEvent e) {
//setText of JLabel here every second/
}
});
Then call
timer.start();
when you want to start calculating the elapsed time which I would assume you want it at the start of the program.. So I would just call this method in the gameLoop, if the Timer hasn't already been started.
Heres the API:
https://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.