1

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();

}
}
4

1 回答 1

3

您的程序没有用来继续 Timer 的 Swing 事件线程。您需要将其放入可视化的 Swing GUI 中以启动 Swing 事件调度线程,然后启动计时器。这可以通过像显示 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");

   }
}
于 2014-08-13T23:22:44.340 回答