gpt4 book ai didi

JavaFX 表行更新

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:10 26 4
gpt4 key购买 nike

我想要实现的场景是,

  1. 每当 TableRow 中的特定 TableCell 更新时,行颜色将更改为红色,3 秒后该颜色应自动恢复为原始颜色。

下面是MCVE

主类

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;

public class TestProjectWin10 extends Application {
private final ObservableList<Element> data = FXCollections.observableArrayList();

public final Runnable changeValues = () -> {
int i = 0;
while (i <= 100000) {
if (Thread.currentThread().isInterrupted()) {
break;
}
data.get(0).setOccurence(System.currentTimeMillis());
data.get(0).count();
i = i + 1;
}
};

private final ExecutorService executor = Executors.newSingleThreadExecutor(runnable -> {
Thread t = new Thread(runnable);
t.setDaemon(true);
return t;
});

@Override
public void start(Stage primaryStage) {

TableView<Element> table = new TableView<>();
table.getStylesheets().add(this.getClass().getResource("tableColor.css").toExternalForm());
table.setEditable(true);

TableColumn<Element, String> nameCol = new TableColumn<>("Name");
nameCol.setPrefWidth(200);
nameCol.setCellValueFactory(cell -> cell.getValue().nameProperty());
nameCol.setCellFactory((TableColumn<Element, String> param) -> new ColorCounterTableCellRenderer(table));
table.getColumns().add(nameCol);

this.data.add(new Element());
table.setItems(this.data);

this.executor.submit(this.changeValues);

Scene scene = new Scene(table, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}

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

元素类:

import java.util.concurrent.atomic.AtomicReference;

import javafx.application.Platform;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class Element {
int x = 0;

private final StringProperty nameProperty = new SimpleStringProperty("");

private final AtomicReference<String> name = new AtomicReference<>();

private final DoubleProperty occurence = new SimpleDoubleProperty();

public void count() {
x = x + 1;
if (name.getAndSet(Integer.toString(x)) == null) {
Platform.runLater(() -> nameProperty.set(name.getAndSet(null)));
}
}

public void setOccurence(double value) {
occurence.set(value);
}

public String getName() {
return nameProperty().get();
}

public void setName(String name) {
nameProperty().set(name);
}

public StringProperty nameProperty() {
return nameProperty;
}

double getOccurrenceTime() {
return occurence.get();
}
}

CellFactory代码:

import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;

public class ColorCounterTableCellRenderer extends TableCell<Element, String> {

private final static long MAX_MARKED_TIME = 3000;
private final static long UPDATE_INTERVAL = 1000;

private static Timer t = null;
private final String highlightedStyle = "highlightedRow";

private final TableView tv;

public ColorCounterTableCellRenderer(TableView tv) {
this.tv = tv;
createTimer();
setAlignment(Pos.CENTER_RIGHT);
}

private void createTimer() {
if (t == null) {
t = new Timer("Hightlight", true);
t.schedule(new TimerTask() {
@Override
public void run() {

final long currentTime = System.currentTimeMillis();

TableRow tr = getTableRow();
if (tr.getItem() != null) {

if (currentTime - ((Element) tr.getItem()).getOccurrenceTime() > MAX_MARKED_TIME) {
Platform.runLater(() -> {
tr.getStyleClass().remove(highlightedStyle);
});
}
}
}
}, 0, UPDATE_INTERVAL);
}
}

@Override
protected void updateItem(String item, boolean empty) {
if (empty || getTableRow() == null || getTableRow().getItem() == null) {
setText(null);
return;
}

long currentTime = System.currentTimeMillis();

TableRow<Element> row = getTableRow();
Element elementRow = row.getItem();

double occurrenceTime = elementRow.getOccurrenceTime();

if (currentTime - occurrenceTime < MAX_MARKED_TIME) {
if (!row.getStyleClass().contains(highlightedStyle)) {
row.getStyleClass().add(highlightedStyle);
}
}

super.updateItem(item, empty);
setText(item + "");

}
}

和 css 文件 tableColor.css

.highlightedRow {
-fx-background-color: rgba(255,0,0, 0.25);
-fx-background-insets: 0, 1, 2;
-fx-background: -fx-accent;
-fx-text-fill: -fx-selection-bar-text;
}

有什么问题..?

  1. 我检查当前时间和更新发生时间之间的差异是否小于 3 秒 - 行颜色为红色(在 ColorCounterTableCellRenderer - updateItem 方法中)

  2. 在单独的计时器 (ColorCounterTableCellRenderer) 中,我尝试检查当前时间和更新发生时间之间的差异是否超过 3 秒 - 移除红色。

但在计时器(createTimer - 方法)代码中:tr.getItem() 始终为 null,因此不会移除红色.

这是实现我想要的目标的正确方法吗?为什么 tr.getItem() 返回 null

测试:我运行代码并等待 executor 代码结束并检查红色是否在 3 秒后被移除。

最佳答案

UI 的任何更新,即使它是通过监听器触发的,也需要从应用程序线程完成。 (您可以通过使用 Platform.runLater 进行更新来解决这个问题。)

此外,您不能依赖同一个单元格在它应该显示为已标记的完整时间内保持同一个单元格。

要克服这个问题,您需要将有关标记单​​元格的信息存储在项目本身或某些可观察的外部数据结构中。

以下示例将上次更新的时间存储在 ObservableMap 中,并使用 AnimationTimer 清除 map 中的过期条目。此外,它使用 TableRow 根据 map 的内容更新伪类。

private static class Item {

private final IntegerProperty value = new SimpleIntegerProperty();
}

private final ObservableMap<Item, Long> markTimes = FXCollections.observableHashMap();
private AnimationTimer updater;

private void updateValue(Item item, int newValue) {
int oldValue = item.value.get();
if (newValue != oldValue) {
item.value.set(newValue);

// update time of item being marked
markTimes.put(item, System.nanoTime());

// timer for removal of entry
updater.start();
}
}

@Override
public void start(Stage primaryStage) {
Item item = new Item(); // the item that is updated
TableView<Item> table = new TableView<>();
table.getItems().add(item);

// some additional items to make sure scrolling effects can be tested
IntStream.range(0, 100).mapToObj(i -> new Item()).forEach(table.getItems()::add);

TableColumn<Item, Number> column = new TableColumn<>();
column.getStyleClass().add("mark-column");
column.setCellValueFactory(cd -> cd.getValue().value);
table.getColumns().add(column);

final PseudoClass marked = PseudoClass.getPseudoClass("marked");

table.setRowFactory(tv -> new TableRow<Item>() {

final InvalidationListener reference = o -> {
pseudoClassStateChanged(marked, !isEmpty() && markTimes.containsKey(getItem()));
};
final WeakInvalidationListener listener = new WeakInvalidationListener(reference);

@Override
protected void updateItem(Item item, boolean empty) {
boolean wasEmpty = isEmpty();
super.updateItem(item, empty);

if (empty != wasEmpty) {
if (empty) {
markTimes.removeListener(listener);
} else {
markTimes.addListener(listener);
}
}

reference.invalidated(null);
}

});

Scene scene = new Scene(table);
scene.getStylesheets().add("style.css");
primaryStage.setScene(scene);
primaryStage.show();

updater = new AnimationTimer() {

@Override
public void handle(long now) {
for (Iterator<Map.Entry<Item, Long>> iter = markTimes.entrySet().iterator(); iter.hasNext();) {
Map.Entry<Item, Long> entry = iter.next();

if (now - entry.getValue() > 2_000_000_000L) { // remove after 1 sec
iter.remove();
}
}

// pause updates, if there are no entries left
if (markTimes.isEmpty()) {
stop();
}
}
};

final Random random = new Random();

Thread t = new Thread(() -> {

while (true) {
try {
Thread.sleep(4000);
} catch (InterruptedException ex) {
continue;
}
Platform.runLater(() -> {
updateValue(item, random.nextInt(4));
});
}
});
t.setDaemon(true);
t.start();
}

样式.css

.table-row-cell:marked .table-cell.mark-column {
-fx-background-color: red;
}

关于JavaFX 表行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52519470/

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