Reputation: 13
I'm trying to stop the program for a second using Swing Timer.
Timer timer = new Timer(10000,
new ActionListener(public void actionPerformed(ActionEvent e) {}));
didn't work
public class Card extends JButton implements ActionListener {
int numberClick = 0;
public card() {
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
numberClick++;
if(numberClick == 2) {
Timer timer = new Timer(10000, );
timer.start();
numberClick = 0;
}
}
}
Upvotes: 1
Views: 93
Reputation: 209112
You seem to lack basic understanding of how the Timer works. Please read How to Use Swing Timers. The concept is fairly simple.
The first argument in the Timer
constructor is the delay
. Seems you have that part down. The second argument is the ActionListener
that listens for the "Timer Events" (actually ActionEvents). An event is fired each delayed time. The callback (actionPerformed
) contains what should be performed after that delay (tick). So whatever you want to happen after that second, put it in the actionPerformed
of the timer's ActionListener
.
Also if you only want it t occur once, you should call timer.setRepeats(false);
. Also note, you are using 10000
, which is in milliseconds, so it's 10 seconds, not 1. You should change it to 1000
Example Flow
JButton button = new JButton("Press Me");
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
Timer timer = new Timer(1000, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Print after one second");
}
});
timer.setRepeats(false);
timer.start();
}
});
Press Button → Wait One Second → Print Statement
Upvotes: 2