所以我试图添加一个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();
}
}
我有一个我的绘画功能的线程,因为我的程序需要不断重画画布。
答案 0 :(得分:0)
解决方案是将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