简体   繁体   中英

How do I use actionListeners without JButtons?

I was reading the documentation on swing timers, when I came across some information about ActionListener s. When further researched, all I could find is how to create an ActionListener attached to a JButton , etc. How can you create a plain ActionListener , not attached to anything?

My timer is not working correctly, and I thought it may be because I was incorrectly using the ActionListener .

Here is my code:

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

public class MyTimer {

    ActionListener al = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            System.out.println("testing");
        }
    };

    public MyTimer() {

        Timer timer = new Timer(10, al);
        timer.start();
    }

    public static void main(String[] args) {
        MyTimer start = new MyTimer();
    }
}

An ActionListener is just an interface

You can create an stand alone version by implementing it and then instanstanting it....

public class MyActionHandler implements ActionListener {
    public void actionPerformed(ActionEvent evt) {
        // do something...
    }
}

And sometime in the future...

MyActionHandler handler = new MyActionHandler();

Or you could create an anonymous instance....

ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        // do something...
    }
};

Take a look at Interfaces for more details

How can you create a plain actionlistner, not attached to anything?

Loot at this:

ActionListener listener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println("Hello World!");
    }
};

// Using the listener with 2 seconds delay
java.swing.Timer timer = new java.swing.Timer(2000, listener);
timer.setRepeats(false);

// Start the timer
timer.start();

Try with this:

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

import javax.swing.Timer;

public class MyTimer {
    ActionListener al = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            System.out.println("testing");
        }
    };

    public MyTimer() {
        Timer timer = new Timer(1000, al);
        timer.start();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                 new MyTimer();
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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