【问题标题】:Time elapsed on canvas java画布java上经过的时间
【发布时间】:2016-09-03 07:08:25
【问题描述】:

所以我想添加一个 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();
       }
    }

我的绘制函数有一个线程,因为我的程序需要不断地重新绘制画布。

【问题讨论】:

    标签: java user-interface canvas timer jlabel


    【解决方案1】:

    一种解决方案是将 Jlabel 添加到扩展框架的类中。

    JLabel lbl = new JLabel("Text"); // instance variable
    this.add(lbl); // this should go in constructor
    

    然后随着时间的推移,您将更新 JLabel 中的文本

    lbl.setText("Time");
    

    然后在您的游戏循环中,您将启动一个 Timer/Swing Timer 并在触发时间操作时更改 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();
    

    当您想开始计算经过的时间时,我会假设您在程序开始时需要它。所以如果 Timer 尚未启动,我会在 gameLoop 中调用此方法。

    这是 API:

    https://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html

    【讨论】:

    • 你好,我已经有一个动作监听器,我应该在里面添加计时器吗?
    • @XaelYvette 如果是这样,那么你的答案是肯定的。将 actionlistener 添加到计时器
    • 不,这是我的菜单栏
    • 如何创建计时器对象?
    • 我应该在我的画布文件中创建计时器对象还是在 jframe 下创建?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多