Java: Countdown und Timer (am Beispiel von Swing)

Posted: Dezember 21st, 2012 | Filed under: Java, Programmieren | Tags: , , , , , , | 12 Comments »

Häufig benötigt man für Applikationen einen Zeitnehmer, oder es soll ein bestimmtes Event nach einer gewissen Zeit ausgeführt werden. Mit Hilfe der Klasse Timer aus der Swing-Bibliothek kann ein sogenannter Countdown leicht erstellt werden. Das folgende Beispiel veranschaulicht die Realisierung eines Countdowns.

Screenshot

image

Quellcode

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 mit 42 Sekunden
  public static int counterValue = 42;
  public static Timer timer;
  public static JLabel label;
 
  public Countdown() {
    initGUI();
  }
 
  // GUI-Erzeugen
  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) {
    // GUI erzeugen
    Countdown countdown = new Countdown();
   
    // Timer erzeugen, jede 1000 Millisekunden (= 1 Sekunde)
    // Methode actionPerformed aufrufen.
    Countdown.timer = new Timer(1000, new ActionListener() {
     
      public void actionPerformed(ActionEvent e) {
        // 1 Sekunde abziehen
        Countdown.counterValue--;
       
        // Zahl in Label darstellen
        Countdown.label.setText(String.valueOf(counterValue));
       
        // Falls Zähler = 0, Countdown abgelaufen!
        if(Countdown.counterValue == 0){
          System.out.println("Counterdown ausgelaufen!");
         
          // Timer stoppen
          Countdown.timer.stop();
        }
      }
    });
       
    // Timer starten
    timer.start();
  }
}

In der Klasse Timer kann im Konstruktor ein Zeitwert und ein Listener übergeben werden. Die actionPerformed-Methode dieses Listeners wird, nachdem der Timer gestartet wurde, alle 1000 ms (=1 s), aufgerufen. Die Methode actionPerfomed ist also unser Taktgeber beim Abziehen einer Sekunde von der aktuellen Countdown-Zahl. Erreicht unsere Zahl den Wert 0, ist der Countdown schließlich abgelaufen.


12 Comments on “Java: Countdown und Timer (am Beispiel von Swing)”

  1. 1 Rufus L. Vasquez said at 17:13 on Januar 16th, 2013:

    Drei ist die sicherste und genaueste Ansatz, meiner Meinung nach. Sie können machen Ihre Anwendung reagieren zu fühlen, indem sichtlich darauf hinweist, dass von Daten auf das erste Resize-Ereignis laden, und passen Sie den Countdown timer um das Gefühl Ihrer Anwendung richtig.

  2. 2 panda said at 08:24 on Juli 15th, 2014:

    I dont get it

  3. 3 Maik said at 21:18 on September 26th, 2014:

    bin gerade am java lernen und hab mal rumgespielt mit deinem code. Gefällt mir – danke 🙂

  4. 4 admin said at 11:04 on September 27th, 2014:

    Vielen Dank fürs positive Feedback!

  5. 5 BillyMockridg said at 12:24 on Mai 24th, 2015:

    I noticed your page’s ranking in google’s search results is very low.
    You are loosing a lot of traffic. You need hi authority backlinks to rank in top10.
    I know – buying them is too expensive. It is better to own them.

    I know how to do that, simply google it:
    Polswor’s Backlinks Source

  6. 6 PENNISKOPF said at 09:36 on September 16th, 2016:

    danle für diesen CODE
    WEITER SO!
    #pennisarmy

  7. 7 PenneyX said at 23:38 on August 15th, 2017:

    Hello admin i see you don’t earn on your page. You can earn extra money easily, search
    on youtube for: how to earn selling articles

  8. 8 LastPenny said at 19:11 on Januar 5th, 2018:

    I have noticed you don’t monetize your page, don’t waste your traffic, you can earn extra cash every month because you’ve
    got high quality content. If you want to know how to make extra
    bucks, search for: Mertiso’s tips best adsense alternative

  9. 9 ChristelSmall said at 20:44 on Januar 30th, 2018:

    I have checked your website and i have found some duplicate content, that’s why you don’t rank high in google,
    but there is a tool that can help you to create 100% unique
    content, search for: Boorfe’s tips unlimited content

  10. 10 ReynaldoBold said at 11:57 on Juni 9th, 2018:

    I have checked your page and i’ve found some duplicate content,
    that’s why you don’t rank high in google, but there is a tool that can help you to create 100% unique
    articles, search for: SSundee advices unlimited content for your
    blog

  11. 11 BestShirleen said at 05:06 on August 10th, 2018:

    I have noticed you don’t monetize your page, don’t waste your traffic, you can earn extra bucks
    every month. You can use the best adsense alternative for any type of website
    (they approve all websites), for more info simply search in gooogle: boorfe’s tips monetize your website

  12. 12 www.awwwards.com said at 20:01 on Februar 8th, 2021:

    May I just say what a comfort to discover someone who really
    understands what they’re talking about on the web. You certainly
    realize how to bring a problem to light and make it important.
    More people need to read this and understand this side of the story.
    I can’t believe you aren’t more popular because you certainly possess
    the gift.


Leave a Reply