简体   繁体   English

无法在[java]中执行计时器

[英]Unable to execute timer in [java]

I've been trying to get down the basics of using a timer so that I can create a bouncing ball program, but I can't seem to implement a timer correctly. 我一直试图了解使用计时器的基础知识,这样我就可以创建一个弹跳球程序,但我似乎无法正确实现计时器。 This program should in theory just continuously print the display, but instead the program simply terminates. 理论上,该程序应该连续打印显示,但程序只是终止。 What can I do to remedy this issue and fix the timer? 我该怎么做才能解决这个问题并修复计时器?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.JFrame;


public class DisplayStuff {

public static void main(String[] args) {


    class TimerListener implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            System.out.println("Display me.");
        }
    }

    ActionListener listener = new TimerListener();
    Timer t= new Timer(1000, listener);
    t.start();

}
}

Your program has no Swing event thread with which to continue the Timer. 您的程序没有用于继续Timer的Swing事件线程。 You need to put it into a visualized Swing GUI to start the Swing event dispatch thread, and then start the timer. 您需要将其放入可视化的Swing GUI中以启动Swing事件调度线程,然后启动计时器。 This could be achieved by something as simple as displaying a JOptionPane: 这可以通过显示JOptionPane这样简单的事情来实现:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;
import javax.swing.Timer;
import javax.swing.JFrame;

public class DisplayStuff {

   public static void main(String[] args) {

      class TimerListener implements ActionListener {
         public void actionPerformed(ActionEvent event) {
            System.out.println("Display me.");
         }
      }

      ActionListener listener = new TimerListener();
      Timer t = new Timer(1000, listener);
      t.start();

      // ***** add just this *****
      JOptionPane.showMessageDialog(null, "foo");

   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM