[英]Time elapsed on canvas java
所以我试图添加一个Jlabel来显示我的程序上的时间,但我不知道在哪里放它以及如何添加一个。 我尝试使用我找到的代码之一,我的程序刚挂了。 希望你能帮我:
这是我的代码的要点,我的GUI有2个独立的java文件
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();
}
这是我绘制图像的画布:
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();
}
}
我有一个我的绘画功能的线程,因为我的程序需要不断重画画布。
解决方案是将Jlabel添加到扩展帧的类中。
JLabel lbl = new JLabel("Text"); // instance variable
this.add(lbl); // this should go in constructor
然后随着时间的推移,您将更新JLabel中的文本
lbl.setText("Time");
然后在你的游戏循环中,你将启动一个定时器/摇摆计时器,并在触发时间动作时更改JLabel的文本...
Timer timer = new Timer(1000, new ActionListener() { //Change parameters to your needs.
@Override
public void actionPerformed(ActionEvent e) {
//setText of JLabel here every second/
}
});
然后打电话
timer.start();
当你想要开始计算经过的时间时我会假设你想要它在程序的开头。所以我只是在gameLoop中调用这个方法,如果Timer还没有被启动。
继承人API:
https://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.