Amrmsmb
Amrmsmb

Reputation: 11406

Actionlistener of a Timer object displays nothing

i am usin the timer class and in the docs it is written that i should import javax.swing.Timer to use it. does it mean that i can not use it in my normal java file? because i tried the below code, and it displays nothing:

static ActionListener timeStampListener = new ActionListener() {

    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
        System.out.println("action listener");
        for (int i = 1; i <= logfile.getTotalLines(); i++) {
            System.out.println("Engine Time(ms): " +  
            logfile.getFileHash().get(i).getTimeStampInSec());
        }
    }
};

    Timer t = new Timer(2, timeStampListener);
    t.setRepeats(true);
    t.start();

Upvotes: 2

Views: 66

Answers (2)

Madhawa Priyashantha
Madhawa Priyashantha

Reputation: 9880

the problem is your main thread exist before starting timer thread .since your application is non-gui use util.Timer instead Swing.Timer ..if you want to work this code using swing timer then add a swing component .add new jframe() and see it's working ..you don't need swing.timer use util timer .

   static ActionListener timeStampListener1 = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("hi");
        }
    };

    public static void main(String[] args) {
        new JFrame(); //add this line
        Timer t = new Timer(2, timeStampListener1);
        t.setRepeats(true);
        t.start();

    }

or give some times by adding thread.sleep to timer to on and see it's working

    Timer t = new Timer(2, timeStampListener1);
    t.setRepeats(true);
    t.start();
    Thread.sleep(1000);


this is how can u use util timer for this

imports

import java.util.Timer;
import java.util.TimerTask;

code

public static void main(String[] args) {

        Timer timer = new Timer();

        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                System.out.println("action listener");
                for (int i = 1; i <= logfile.getTotalLines(); i++) {
                    System.out.println("Engine Time(ms): "
                            + logfile.getFileHash().get(i).getTimeStampInSec());
                }
            }
        }, 500, 2);
    }

Upvotes: 1

halit
halit

Reputation: 177

No, it means that you should import which Timer class you will use. When you import javax.swing.Timer you specifies Timer class in javax.swing package. You can use it in your java file.

Anyway, have you tried not using static keyword with your timeStampListener?

Upvotes: 0

Related Questions