gpt4 book ai didi

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

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

我在尝试弄清楚如何使 TableView 根据每个条目响应状态显示正确的数据时遇到问题。我以为 FilteredList 可以完成工作,但事实并非如此。基本上,我正在检查 URL 并获取它们的状态代码。我使用 FilteredList 来显示所有待处理、已成功等的 URL。如果我将 ChoiceBoxAll 更改为 Pending 时,FilteredList 仅显示待处理的 URL,但当 URL 更改为 Success 或其他内容时,FilteredList 不会显示将它们过滤掉当前 View 。应该发生的情况是,当我更改为 Pending 时,任何接收状态更改的 URL 都应该从当前 View 中删除。如何让 FilteredList/TableView 进行实时更新?

主要

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

}

Controller

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

该程序使用 Apache HttpComponents .

网址列表

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

如果程序结束得很快,可能需要循环浏览列表几次。

最佳答案

只要 Predicate 发生变化,FilteredList 就会更新,只要它检测到源 ObservableList 发生变化。您想要触发的事件类型是 update事件。此事件表示一个或多个元素已更新(例如,当属性更改时)。为此,您必须使用适当的工厂方法构造 ObservableList:FXCollections.observableArrayList(Callback) .

此工厂方法采用 Callback它接受 ObservableList 的元素并返回 Observable[]。将监听数组中的 Observable 是否有失效事件,并且在检测到时,将导致 ObservableList 触发更新更改。

从代码来看,似乎1 Model 类具有 status 属性。如果您想在状态更改时触发更新,您应该使用:

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

如果您希望触发更新而不仅仅是对 status 属性进行更改,则可以向数组中添加更多 Observable

现在,当 status 属性更改时,FilteredList 将注意到并根据需要过滤元素。

<小时/>

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

关于java - 状态更改时删除 TableView 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51955550/

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