有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在状态更改时删除TableView条目

我在试图找出如何使TableView根据每个条目响应状态显示正确的数据时遇到了一个问题。我原以为FilteredList能完成这项工作,但事实并非如此。基本上,我是在检查URL并获取它们的状态码。我正在使用FilteredList来显示所有挂起的、成功的URL,等等。如果我将ChoiceBoxAll更改为Pending,那么FilteredList只显示挂起的URL,但是当URL更改为Success或其他内容时,^}不会从当前视图中过滤掉它们。当我更改为Pending时,任何接收到状态更改的URL都应该从当前视图中删除。如何让FilteredList/TableView进行实时更新

Main

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication240 extends Application
{

    @Override
    public void start(Stage stage) throws Exception
    {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

}

控制器

import com.sun.javafx.application.HostServicesDelegate;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;

/**
 *
 * @author blj0011
 */
public class FXMLDocumentController implements Initializable
{

    @FXML
    private Button btnProcess;
    @FXML
    private TableView<Model> tvMain;
    @FXML
    private TableColumn<Model, String> tcBibId, tcHoldingId, tcUrl, tcStatus;
    @FXML
    private TableColumn<Model, Integer> tcId;
    @FXML
    private ChoiceBox<String> cbMain;

    private final ObservableList<Model> masterData = FXCollections.observableArrayList();
    FilteredList<Model> filteredData;
    HostServicesDelegate hostServicesDelegate;
    AtomicInteger processUrlCounter;
    int tableViewSize = -1;
    AtomicInteger seconds = new AtomicInteger();

    @Override
    public void initialize(URL url, ResourceBundle rb)
    {
        // TODO
        processUrlCounter = new AtomicInteger();
        setupChoiceBox();
        setupTableView();
        btnProcess.setOnAction((event) -> {
            btnProcess.setDisable(true);
            List<Task<String>> tasks = new ArrayList();
            tvMain.getItems().forEach((t) -> {
                Model tempModel = (Model) t;
                tasks.add(processUrl(tempModel));
            });

            tasks.forEach(exec::execute);
        });
    }

    private List<Model> getTestData()
    {
        List<Model> testList = new ArrayList();
        Random random = new Random();

        try (Scanner input = new Scanner(new File("testdata.txt"))) {
            while (input.hasNext()) {
                Model tempModel = new Model(Integer.toString(random.nextInt(100000) + 100000), Integer.toString(random.nextInt(100000) + 100000), input.next());
                testList.add(tempModel);
                System.out.println(tempModel.toString());
            }
        }
        catch (FileNotFoundException ex) {
            Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
        }

        return testList;
    }

    private void setupChoiceBox()
    {
        List<String> STATUS_LIST = Arrays.asList("ALL", "PENDING", "SUCCESS");

        cbMain.getItems().addAll(STATUS_LIST);
        cbMain.getSelectionModel().selectFirst();
        cbMain.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal)
                -> {
            List<Model> tempList = new ArrayList();
            switch (newVal) {
                case "ALL":
                    tempList = tvMain.getItems();
                    filteredData.setPredicate(null);
                    break;
                case "PENDING":
                    filteredData.setPredicate((t) -> {
                        return t.getStatus().trim().equals("PENDING");
                    });
                    tempList = tvMain.getItems().filtered((t) -> {
                        return t.getStatus().equals("PENDING");
                    });
                    break;
                case "SUCCESS":
                    filteredData.setPredicate((t) -> {
                        return t.getStatus().trim().matches("2\\d\\d");
                    });
                    tempList = tvMain.getItems().filtered((t) -> {
                        return t.getStatus().matches("2\\d\\d");
                    });
                    break;
            }
        });
    }

    private void setupTableView()
    {
        tcId.setCellValueFactory(new PropertyValueFactory("id"));
        tcBibId.setCellValueFactory(cell -> cell.getValue().bibIdProperty());
        tcHoldingId.setCellValueFactory(cell -> cell.getValue().holdingIdProperty());
        tcUrl.setCellValueFactory(cell -> cell.getValue().urlProperty());
        tcStatus.setCellValueFactory(cell -> cell.getValue().statusProperty());

        masterData.setAll(getTestData());
        filteredData = new FilteredList(masterData, null);
        tvMain.setItems(filteredData);
        tableViewSize = masterData.size();

    }

    private final ExecutorService exec = Executors.newFixedThreadPool(2500, r -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        return t;
    });

    private Task<String> processUrl(Model model)
    {
        Task<String> task = new Task<String>()
        {
            @Override
            protected String call() throws Exception
            {
                CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()).setRedirectStrategy(new LaxRedirectStrategy()).build();

                HttpGet httpGet = new HttpGet(model.getUrl());
                try (CloseableHttpResponse response1 = httpclient.execute(httpGet)) {
                    String tempResponse = response1.getStatusLine().toString().split(" ")[1];

                    return tempResponse;
                }
                catch (IOException ex) {
                    String tempString = ex.getClass().toString().split(" ")[1];
                    String[] tempException = tempString.split("\\.");

                    return tempException[tempException.length - 1];
                }
            }
        };

        task.setOnSucceeded((event) -> {
            model.setStatus(task.getValue());
            if (processUrlCounter.incrementAndGet() == tableViewSize) {
                btnProcess.setDisable(false);
            }
            String tempOutput = "Processed URLs: " + processUrlCounter.get() + " of " + tableViewSize;
        });

        return task;
    }
}

FXML

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ChoiceBox?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.VBox?>

<VBox alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="862.0" prefWidth="748.0" spacing="10.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication240.FXMLDocumentController">
    <children>
        <ChoiceBox fx:id="cbMain" prefWidth="150.0" />
        <TableView fx:id="tvMain" prefHeight="200.0" prefWidth="200.0" VBox.vgrow="ALWAYS">
            <columns>
                <TableColumn fx:id="tcId" prefWidth="85.0" text="ID" />
                <TableColumn fx:id="tcBibId" prefWidth="102.0" text="Bib ID" />
                <TableColumn fx:id="tcHoldingId" prefWidth="113.0" text="Holding ID" />
                <TableColumn fx:id="tcUrl" prefWidth="313.0" text="URL" />
                <TableColumn fx:id="tcStatus" prefWidth="132.0" text="Status" />
            </columns>
        </TableView>
        <Button fx:id="btnProcess" mnemonicParsing="false" text="Process" />
    </children>
    <padding>
        <Insets bottom="10.0" top="10.0" />
    </padding>
</VBox>

模型类

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

/**
 *
 * @author Sedrick
 */
public class Model
{

    final private IntegerProperty id = new SimpleIntegerProperty();
    final private StringProperty bibId = new SimpleStringProperty();
    final private StringProperty holdingId = new SimpleStringProperty();
    final private StringProperty url = new SimpleStringProperty();
    final private StringProperty status = new SimpleStringProperty();

    public Model(int id, String bibId, String holdingID, String url)
    {
        this.id.set(id);
        this.bibId.set(bibId);
        this.holdingId.set(holdingID);
        this.url.set(url);
        this.status.set("PENDING");
    }

    public Model(String bibId, String holdingId, String url)
    {
        this.id.set(-1);
        this.bibId.set(bibId);
        this.holdingId.set(holdingId);
        this.url.set(url);
        this.status.set("PENDING");
    }

    public IntegerProperty idProperty()
    {
        return this.id;
    }

    public StringProperty bibIdProperty()
    {
        return this.bibId;
    }

    public StringProperty holdingIdProperty()
    {
        return this.holdingId;
    }

    public StringProperty urlProperty()
    {
        return this.url;
    }

    public StringProperty statusProperty()
    {
        return this.status;
    }

    public void setId(int id)
    {
        this.id.set(id);
    }

    public void setBibId(String bibId)
    {
        this.bibId.set(bibId);
    }

    public void setHoldingId(String holdingId)
    {
        this.holdingId.set(holdingId);
    }

    public void setUrl(String url)
    {
        this.url.set(url);
    }

    public void setStatus(String status)
    {
        this.status.set(status);
    }

    public int getId()
    {
        return id.get();
    }

    public String getBibId()
    {
        return bibId.get();
    }

    public String getHoldingId()
    {
        return holdingId.get();
    }

    public String getUrl()
    {
        return url.get();
    }

    public String getStatus()
    {
        return status.get();
    }

    @Override
    public String toString()
    {
        return getId() + ": " + getBibId() + " - " + getHoldingId() + " - " + getUrl();
    }
}

该程序使用^{}

URL列表

http://www.youtube.com
http://www.facebook.com
http://www.baidu.com
http://www.yahoo.com
http://www.amazon.com
http://www.wikipedia.org
http://www.qq.com
http://www.google.co.in
http://www.twitter.com
http://www.live.com
http://www.taobao.com
http://www.bing.com
http://www.instagram.com
http://www.weibo.com
http://www.sina.com.cn
http://www.linkedin.com
http://www.yahoo.co.jp
http://www.msn.com
http://www.vk.com
http://www.google.de
http://www.yandex.ru
http://www.hao123.com
http://www.google.co.uk
http://www.reddit.com
http://www.ebay.com
http://www.google.fr
http://www.t.co
http://www.tmall.com
http://www.google.com.br
http://www.360.cn
http://www.sohu.com
http://www.amazon.co.jp
http://www.pinterest.com
http://www.netflix.com
http://www.google.it
http://www.google.ru
http://www.microsoft.com
http://www.google.es
http://www.wordpress.com
http://www.gmw.cn
http://www.tumblr.com
http://www.paypal.com
http://www.blogspot.com
http://www.imgur.com
http://www.stackoverflow.com
http://www.aliexpress.com
http://www.naver.com
http://www.ok.ru
http://www.apple.com
http://www.github.com
http://www.chinadaily.com.cn
http://www.imdb.com
http://www.google.co.kr
http://www.fc2.com
http://www.jd.com
http://www.blogger.com
http://www.163.com
http://www.google.ca
http://www.whatsapp.com
http://www.amazon.in
http://www.office.com
http://www.tianya.cn
http://www.google.co.id
http://www.youku.com
http://www.rakuten.co.jp
http://www.craigslist.org
http://www.amazon.de
http://www.nicovideo.jp
http://www.google.pl
http://www.soso.com
http://www.bilibili.com
http://www.dropbox.com
http://www.xinhuanet.com
http://www.outbrain.com
http://www.pixnet.net
http://www.alibaba.com
http://www.alipay.com
http://www.microsoftonline.com
http://www.booking.com
http://www.googleusercontent.com
http://www.google.com.au
http://www.popads.net
http://www.cntv.cn
http://www.zhihu.com
http://www.amazon.co.uk
http://www.diply.com
http://www.coccoc.com
http://www.cnn.com
http://www.bbc.co.uk
http://www.twitch.tv
http://www.wikia.com
http://www.google.co.th
http://www.go.com
http://www.google.com.ph
http://www.doubleclick.net
http://www.onet.pl
http://www.googleadservices.com
http://www.accuweather.com
http://www.googleweblight.com
http://www.answers.yahoo.com
http://www.youtube.com
http://www.facebook.com
http://www.baidu.com
http://www.yahoo.com
http://www.amazon.com
http://www.wikipedia.org
http://www.qq.com
http://www.google.co.in
http://www.twitter.com
http://www.live.com
http://www.taobao.com
http://www.bing.com
http://www.instagram.com
http://www.weibo.com
http://www.sina.com.cn
http://www.linkedin.com
http://www.yahoo.co.jp
http://www.msn.com
http://www.vk.com
http://www.google.de
http://www.yandex.ru
http://www.hao123.com
http://www.google.co.uk
http://www.reddit.com
http://www.ebay.com
http://www.google.fr
http://www.t.co
http://www.tmall.com
http://www.google.com.br
http://www.360.cn
http://www.sohu.com
http://www.amazon.co.jp
http://www.pinterest.com
http://www.netflix.com
http://www.google.it
http://www.google.ru
http://www.microsoft.com
http://www.google.es
http://www.wordpress.com
http://www.gmw.cn
http://www.tumblr.com
http://www.paypal.com
http://www.blogspot.com
http://www.imgur.com
http://www.stackoverflow.com
http://www.aliexpress.com
http://www.naver.com
http://www.ok.ru
http://www.apple.com
http://www.github.com
http://www.chinadaily.com.cn
http://www.imdb.com
http://www.google.co.kr
http://www.fc2.com
http://www.jd.com
http://www.blogger.com
http://www.163.com
http://www.google.ca

如果程序以fast结尾,则可能需要在列表中循环几次


共 (1) 个答案

  1. # 1 楼答案

    每当一个FilteredListPredicate发生变化时,只要它检测到源ObservableList发生变化,FilteredList就会更新。要激发的事件类型是update事件。此事件表示一个或多个元素已更新(例如,当属性更改时)。为了做到这一点,您必须使用适当的工厂方法来构造ObservableList^{}

    这个工厂方法接受一个^{},它接受ObservableList的一个元素,并返回一个Observable[]。将监听数组中的Observable以查找无效事件,当检测到时,将导致ObservableList触发更新更改

    从你的代码来看,1就像Model类有一个status属性。如果要在status更改时触发更新,则应使用:

    ObservableList<Model> masterData = FXCollections.observableArrayList(model ->
            new Observable[]{model.statusProperty()});
    

    如果您希望为status属性的更改触发更新,那么可以向数组中添加更多Observable

    现在,当status属性更改时,FilteredList将注意到并过滤元素(如果需要)


    1。当我写这个答案时,你还没有发布Model类。然而,我设法从可用代码中对其进行“逆向工程”,并使用Callback提取器对其进行了测试。当status从挂起状态更改为新状态时,元素从FilteredList中删除,从而从TableView中删除