gpt4 book ai didi

java - 我有一个以毫秒为单位表示时间的 Longs 列表。如何创建一个 ListView,在显示它们之前将 Longs 格式化为 MM :SS. LLL?

转载 作者:行者123 更新时间:2023-11-30 07:54:44 25 4
gpt4 key购买 nike

我有一个用多头表示的时间列表。我想在一个 ListView 中显示这些时间,该 ListView 在 Longs 上调用 String.format() 以将它们变成 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 :

cell factory

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

关于java - 我有一个以毫秒为单位表示时间的 Longs 列表。如何创建一个 ListView,在显示它们之前将 Longs 格式化为 MM :SS. LLL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43813930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com