我有一个由朗斯代表的时间清单。我想在调用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()或类似的方法,但每次列表更改时都没有侦听器会重新计算所有值。

最佳答案

使用cell factory

java - 我有一个代表毫秒的Longs列表。如何显示将Longs格式化为MM:SS.LLL的ListView?-LMLPHP

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);
    }
}

10-06 09:35