我如何格式化将在标签中的字符串

时间:2017-07-30 00:20:47

标签: java javafx

我有一个媒体播放器,我在我的媒体播放器上放置一个列表器,用于滑块值和时间值我的问题是如何格式化我在标签中显示的时间显示为0:00第一个0是分钟,第二个是10秒,第三个是每秒。

public void setUpsongDurationSlider()
{
    musicMedia.getMediaPlayer().currentTimeProperty().addListener((obs, oldTme, newTime)->
    {
        homeView.getSongDurationSlider().setValue(newTime.toSeconds());
        homeView.getSongDurationSliderLabel().setText(Double.toString((newTime.toMinutes())));
    });
}

2 个答案:

答案 0 :(得分:0)

只需从Duration对象中检索分钟/秒,然后使用String.format填充秒......

以下示例仅打印到System.out并使用代码中创建的属性,但您应该可以根据自己的需要进行调整:

ObjectProperty<Duration> duration = new SimpleObjectProperty(Duration.ZERO);

duration.addListener((observable, oldValue, newValue) -> {
    System.out.println(String.format("%d:%02d",
            (long)newValue.toMinutes(),
            ((long) newValue.toSeconds()) % 60));
});

// test for 1-99 seconds
for (int i = 1; i < 100; i++) {
    duration.set(Duration.seconds(i));
}

答案 1 :(得分:-1)

所以其他帖子有所帮助,但它是需要转换的双倍值,所以我需要使用“%f”而不是“%d”。

musicMedia.getMediaPlayer().currentTimeProperty().addListener((obs, oldTme, newTime)->
        {
            homeView.getSongDurationSlider().setValue(newTime.toSeconds());
            homeView.getSongDurationSliderLabel().setText(String.format("%.2f min",(newTime.toMinutes())));
相关问题