summaryrefslogtreecommitdiffstats
path: root/src/de/fhswf/in/inf/java2/aufgabe04/CountdownExitButton.java
blob: b859b8febc88341229f96deea439d46e0e23ca8a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
 * File for the CountdownExitButton class.
 */

package de.fhswf.in.inf.java2.aufgabe04;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.control.Button;
import javafx.util.Duration;

/**
 * A class that fires automatically after a given interval.
 *
 * @author Stefan Suhren
 * @version 1.0
 */
public class CountdownExitButton extends Button
{

   private int countdown = 30;

   private Timeline timeline = new Timeline();

   /**
    * A Button that exits the application.
    *
    * @param text
    *           The text that will be displayed
    * @param countdown
    *           The time in seconds till the button fires
    */
   public CountdownExitButton(String text, int countdown)
   {
      super(text);
      setCountdown(countdown);

      timeline.setCycleCount(Timeline.INDEFINITE);
      timeline
            .getKeyFrames()
            .add(new KeyFrame(
               Duration.seconds(1),
               (e -> {
                  CountdownExitButton.this
                        .setText(CountdownExitButton.this
                              .getText()
                              .replaceFirst(
                                    "\\("
                                          + CountdownExitButton.this.countdown
                                          + "\\)$",
                                    "("
                                          + --CountdownExitButton.this.countdown
                                          + ")"));
                  if (CountdownExitButton.this.countdown <= 0)
                  {
                     CountdownExitButton.this.fire();
                  }
               })));
   }

   /**
    * Starts the countdown.
    *
    */
   public void startCountdown()
   {
      super.setText(getText() + " (" + countdown + ")");
      timeline.playFromStart();
   }

   /**
    * Set the countdown.
    *
    * @param countdown
    *           The time in seconds till the button fires.
    */
   public void setCountdown(int countdown)
   {
      if (countdown < 0)
      {
         throw new IllegalArgumentException("Countdown can't be negative.");
      }
      this.countdown = countdown;
   }

   /**
    * Get the countdown.
    *
    * @return
    * The countdown in seconds.
    */
   public int getCountdown()
   {
      return countdown;
   }

}