Reputation: 1
I make a simple application which contain a quiz questions and the user select an answer but i need your help in adding a count down timer in my app for 20 sec when this time is up it will transfer directly to the next question and when the user answer in time it will transfer to next question
Thank you
Upvotes: 0
Views: 105
Reputation: 10288
The "Android way" to do timed things is by posting Runnable
tasks to a Handler.
Upvotes: 0
Reputation: 277
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.WindowConstants;
public class Countdown extends JFrame {
// Countdown 42 seconds
public static int counterValue = 42;
public static Timer timer;
public static JLabel label;
public Countdown() {
initGUI();
}
private void initGUI(){
BorderLayout thisLayout = new BorderLayout();
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.getContentPane().setLayout(thisLayout);
label = new JLabel();
label.setText(String.valueOf(counterValue));
this.getContentPane().add(label, BorderLayout.CENTER);
this.setTitle("Countdown Example");
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
Countdown countdown = new Countdown();
Countdown.timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
// =1 sec
Countdown.counterValue--;
Countdown.label.setText(String.valueOf(counterValue));
if(Countdown.counterValue == 0){
System.out.println("Counterdown ausgelaufen!");
// Timer stop
Countdown.timer.stop();
}
}
});
// Timer start
timer.start();
}
}
Taken from http://blog.mynotiz.de/programmieren/java-countdown-und-timer-am-beispiel-von-swing-1707/ ( German )
Upvotes: 1