簡體   English   中英

我有一個代表毫秒的Longs列表。 如何顯示將Longs格式化為MM:SS.LLL的ListView?

[英]I have a list of Longs that represent time in milliseconds. How can I create a ListView that formats the Longs into MM:SS.LLL before displaying them?

我有一個由朗斯代表的時間清單。 我想在調用Longs上的String.format()的ListView中顯示這些時間,以使其成為MM:SS.LLL字符串。

我在想這樣的事情:

ObservableList<Long> scores = FXCollections.observableArrayList();
//add a few values to scores...
scores.add(123456);
scores.add(5523426);
scores.add(230230478);

//listen for changes in scores, and set all values of formattedScores based on scores values.
ObservableList<String> formattedScores = FXCollections.observableArrayList();
scores.addListener(o -> {
    formattedScores.clear();
    for (Long score : scores) {
        formattedScores.add(String.format("%1$tM:%1$tS.%1$tL", String.valueOf(score)));
    }
});

//create an object property that can be bound to ListView.
ObjectProperty<ObservableList<String>> scoresObjProperty = ObjectProperty<ObservableList<String>>(formattedScores);

ListView<String> listView = new ListView<>();
listView.itemsProperty().bind(scoresObjProperty);

我覺得有一個更好的解決方案,但是,也許使用Bindings.format()或類似的方法,但每次列表更改時都沒有偵聽器會重新計算所有值。

使用細胞工廠

細胞工廠

import javafx.application.Application;
import javafx.collections.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;

import java.util.Calendar;

public class TimeList extends Application {
    @Override
    public void start(final Stage stage) throws Exception {
        ObservableList<Long> scores = FXCollections.observableArrayList();
        //add a few values to scores...
        scores.add(123456L);
        scores.add(5523426L);
        scores.add(230230478L);

        ListView<Long> listView = new ListView<>(scores);
        listView.setCellFactory(param -> new ListCell<Long>() {
            @Override
            protected void updateItem(Long item, boolean empty) {
                super.updateItem(item, empty);

                if (item != null && !empty) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(item);
                    String formattedText = String.format("%1$tM:%1$tS.%1$tL", calendar);

                    setText(formattedText);
                } else {
                    setText(null);
                }
            }
        });

        listView.setPrefSize(100, 100);

        stage.setScene(new Scene(listView));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM