首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JavaFX表行更新

JavaFX表行更新
EN

Stack Overflow用户
提问于 2018-09-26 21:55:56
回答 2查看 2.7K关注 0票数 5

我想要实现的场景是,

  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. I检查当前时间与更新发生时间之间的差异是否小于3秒- ColorCounterTableCellRenderer - updateItem方法中行颜色变为红色(在ColorCounterTableCellRenderer-updateItem方法中)
  2. 在单独的计时器(ColorCounterTableCellRenderer)中,我尝试检查当前时间与更新发生时间之间的差异是否大于3秒-删除红色。

但在定时器(createTimer - tr.getItem() )代码中:方法总是null,因此不会删除红色。

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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-09-27 01:07:59

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

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

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

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

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

style.css

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

Stack Overflow用户

发布于 2018-09-27 08:24:59

我同意@kleopatra的评论。您不能在单元格中进行复杂的数据处理。大多数情况下,你的Row/Cell/updateItem()应该更多地关注“如何呈现/呈现什么”。我可以建议你一些关键的方向,你可以看看。

如果您想要基于项中的某些更新来更新行样式(不是因为添加/删除项,而是因为项的属性中的更新),您必须首先侦听更改。

仅在ObservableList上设置ListChangeListener不会通知您“在”属性内发生的任何更改。您必须将您的ObservableList注册到您感兴趣的属性中,并且在更新时需要得到通知。因此,您要在TableView中设置的ObservableList应该注册/声明如下:

    ObservableList<Person> persons = FXCollections.observableArrayList(e -> 
                                                      new Observable[]{e.pointsProperty()});

上面的代码在更新ObservableList时强制触发pointsProperty的ListChangeListener。在那里,您可以执行所需的操作。

下面是一个快速工作的演示,它在每次更新点列时高亮显示3秒钟的行。我希望这个演示可以给你一些输入来解决你的问题。这是其中的一种方法。可以有更多更好的方法来实现以下功能。你仍然可以使用@fabian解决方案。

css注意:使用与您提供的相同的文件。

import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.Observable;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.Duration;
import java.security.SecureRandom;

public class TableRowUpdateHighlightDemo extends Application {
    private final SecureRandom rnd = new SecureRandom();

    @Override
    public void start(Stage primaryStage) throws Exception {
        ObservableList<Person> persons = FXCollections.observableArrayList(e -> new Observable[]{e.pointsProperty()});
        persons.add(new Person("Harry", "John"));
        persons.add(new Person("Mary", "King"));
        persons.add(new Person("Don", "Bon"));
        persons.add(new Person("Pink", "Wink"));

        TableView<Person> tableView = new TableView<>();
        TableColumn<Person, String> fnCol = new TableColumn<>("First Name");
        fnCol.setCellValueFactory(param -> param.getValue().firstNameProperty());

        TableColumn<Person, String> lnCol = new TableColumn<>("Last Name");
        lnCol.setCellValueFactory(param -> param.getValue().lastNameProperty());

        TableColumn<Person, Integer> pointsCol = new TableColumn<>("Points");
        pointsCol.setCellValueFactory(param -> param.getValue().pointsProperty().asObject());

        tableView.getStylesheets().add(this.getClass().getResource("tableColor.css").toExternalForm());
        tableView.getColumns().addAll(fnCol, lnCol, pointsCol);
        tableView.setItems(persons);
        tableView.getItems().addListener((ListChangeListener<Person>) c -> {
            if (c.next()) {
                if (c.wasUpdated()) {
                    tableView.getItems().get(c.getFrom()).setHightlight(true);
                    tableView.refresh();
                }
            }
        });
        tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        tableView.setRowFactory(new Callback<TableView<Person>, TableRow<Person>>() {
            @Override
            public TableRow<Person> call(TableView<Person> param) {
                return new TableRow<Person>() {
                    Timeline highlightTL;

                    @Override
                    protected void updateItem(Person item, boolean empty) {
                        super.updateItem(item, empty);
                        removeHighlight();
                        if (item != null && item.isHightlight()) {
                            getStyleClass().add("highlightedRow");
                            getHighlightTL().playFromStart();
                        }
                    }

                    private void removeHighlight() {
                        getHighlightTL().stop();
                        getStyleClass().removeAll("highlightedRow");
                    }

                    private Timeline getHighlightTL() {
                        if (highlightTL == null) {
                            // After 3 secs, the hightlight will be removed.
                            highlightTL = new Timeline(new KeyFrame(Duration.millis(3000), e -> {
                                getItem().setHightlight(false);
                                removeHighlight();
                            }));
                            highlightTL.setCycleCount(1);
                        }
                        return highlightTL;
                    }
                };
            }
        });

        Scene sc = new Scene(tableView);
        primaryStage.setScene(sc);
        primaryStage.show();

        // Updating points every 5 secs to a random person.
        Timeline tl = new Timeline(new KeyFrame(Duration.millis(5000), e -> {
            Person p = persons.get(rnd.nextInt(4));
            p.setPoints(p.getPoints() + 1);
        }));
        tl.setCycleCount(Animation.INDEFINITE);
        tl.play();

    }

    class Person {
        private StringProperty firstName = new SimpleStringProperty();
        private StringProperty lastName = new SimpleStringProperty();
        private IntegerProperty points = new SimpleIntegerProperty();
        private BooleanProperty hightlight = new SimpleBooleanProperty();

        public Person(String fn, String ln) {
            setFirstName(fn);
            setLastName(ln);
        }

        public String getFirstName() {
            return firstName.get();
        }

        public StringProperty firstNameProperty() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName.set(firstName);
        }

        public String getLastName() {
            return lastName.get();
        }

        public StringProperty lastNameProperty() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName.set(lastName);
        }

        public int getPoints() {
            return points.get();
        }

        public IntegerProperty pointsProperty() {
            return points;
        }

        public void setPoints(int points) {
            this.points.set(points);
        }

        public boolean isHightlight() {
            return hightlight.get();
        }

        public BooleanProperty hightlightProperty() {
            return hightlight;
        }

        public void setHightlight(boolean hightlight) {
            this.hightlight.set(hightlight);
        }
    }
}

更新::如果您可以设法在外部(3秒后)更新"hightlight“属性值,则不需要在RowFactory中使用时间轴。只需在ListChangeListener中调用tableView.refresh()就可以完成此任务:)

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52519470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档