web-dev-qa-db-fra.com

Affichage des valeurs changeantes dans JavaFx Label

Dans JavaFX, comment puis-je afficher des valeurs qui changent continuellement avec le temps en utilisant "label"?

21
Surjit

Il existe de nombreuses façons d'y parvenir, la plus pratique serait d'utiliser le mécanisme DataBinding de JavaFX:

// assuming you have defined a StringProperty called "valueProperty"
Label myLabel = new Label("Start");
myLabel.textProperty().bind(valueProperty);

De cette façon, chaque fois que votre valeurProperty est modifiée en appelant sa méthode set, le texte de l'étiquette est mis à jour.

25
Sebastian

Que diriez-vous d'utiliser SimpleDateFormat? Il n'y a pas besoin de la classe StringUtilities!

private void bindToTime() {
  Timeline timeline = new Timeline(
    new KeyFrame(Duration.seconds(0),
      new EventHandler<ActionEvent>() {
        @Override public void handle(ActionEvent actionEvent) {
          Calendar time = Calendar.getInstance();
          SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
          setText(simpleDateFormat.format(time.getTime()));
        }
      }
    ),
    new KeyFrame(Duration.seconds(1))
  );
  timeline.setCycleCount(Animation.INDEFINITE);
  timeline.play();
 }
}
13
Blindworks

J'aime la réponse contraignante de Sebastian.

Pour plus de variété, voici un autre exemple de modification d'un texte d'étiquette en fonction du temps. L'exemple affiche une lecture d'horloge numérique dans une étiquette dont le texte change chaque seconde à l'aide d'un Timeline .

import Java.io.IOException;
import Java.net.URL;
import javafx.animation.*;
import javafx.event.*;
import javafx.scene.control.Label;
import javafx.util.Duration;

import Java.util.Calendar;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class DigitalClockSample extends Application {
  public static void main(String[] args) { launch(args); }
  @Override public void start(Stage stage) throws IOException {
    stage.setScene(new Scene(new DigitalClock(), 100, 50));
    stage.show();
  }
}

/**
 * Creates a digital clock display as a simple label.
 * Format of the clock display is hh:mm:ss aa, where:
 * hh Hour in am/pm (1-12)
 * mm Minute in hour
 * ss Second in minute
 * aa Am/pm marker
 * Time is the system time for the local timezone.
 */
class DigitalClock extends Label {
  public DigitalClock() {
    bindToTime();
  }

  // the digital clock updates once a second.
  private void bindToTime() {
    Timeline timeline = new Timeline(
      new KeyFrame(Duration.seconds(0),
        new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent actionEvent) {
            Calendar time = Calendar.getInstance();
            String hourString = StringUtilities.pad(2, ' ', time.get(Calendar.HOUR) == 0 ? "12" : time.get(Calendar.HOUR) + "");
            String minuteString = StringUtilities.pad(2, '0', time.get(Calendar.MINUTE) + "");
            String secondString = StringUtilities.pad(2, '0', time.get(Calendar.SECOND) + "");
            String ampmString = time.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM";
            setText(hourString + ":" + minuteString + ":" + secondString + " " + ampmString);
          }
        }
      ),
      new KeyFrame(Duration.seconds(1))
    );
    timeline.setCycleCount(Animation.INDEFINITE);
    timeline.play();
  }
}

class StringUtilities {
  /**
   * Creates a string left padded to the specified width with the supplied padding character.
   * @param fieldWidth the length of the resultant padded string.
   * @param padChar a character to use for padding the string.
   * @param s the string to be padded.
   * @return the padded string.
   */
  public static String pad(int fieldWidth, char padChar, String s) {
    StringBuilder sb = new StringBuilder();
    for (int i = s.length(); i < fieldWidth; i++) {
      sb.append(padChar);
    }
    sb.append(s);

    return sb.toString();
  }
}

Sortie d'échantillonnage d'horloge numérique:

Digital clock output

10
jewelsea

Excellentes réponses, merci jewelsea pour votre contribution, cela m'a beaucoup aidé.

J'ai mis à jour le DigitalClock publié précédemment dans un format plus léger en utilisant Java 8 . En utilisant les ajouts de Java 8 comme Date API et bien sûr lambdas .

 import javafx.animation.Animation;
 import javafx.animation.KeyFrame;
 import javafx.animation.Timeline;
 import javafx.scene.control.Label;
 import javafx.util.Duration;

 import Java.time.LocalTime;
 import Java.time.format.DateTimeFormatter;

 public class DigitalClock extends Label
 {
    private static DateTimeFormatter SHORT_TIME_FORMATTER =       DateTimeFormatter.ofPattern("HH:mm:ss");

    public DigitalClock()
    {
        bindToTime();
    }

    private void bindToTime() {
        Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0),
                                                      event -> setText(LocalTime.now().format(SHORT_TIME_FORMATTER))),
                                         new KeyFrame(Duration.seconds(1)));

        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();
    }
}
4
Olimpiu POP