如何基于JSoup Service实现超链接ListView展示?
实现方法
1. 自定义ListCell<Element>子类
核心是重写updateItem()方法,从JSoup的<a>标签元素中分离显示文本与链接地址,并构建UI组件展示:
import javafx.scene.control.ListCell; import javafx.scene.control.Hyperlink; import org.jsoup.nodes.Element; import java.awt.Desktop; import java.io.IOException; import java.net.URI; public class LinkCell extends ListCell<Element> { private final Hyperlink hyperlink = new Hyperlink(); @Override protected void updateItem(Element aTag, boolean empty) { super.updateItem(aTag, empty); // 处理空单元格或null数据,避免复用旧内容 if (empty || aTag == null) { setText(null); setGraphic(null); return; } // 提取<a>标签的显示文本与绝对链接 String displayText = aTag.text().trim(); String absoluteUrl = aTag.absUrl("href"); // 自动转换相对链接为绝对链接 // 配置超链接 hyperlink.setText(displayText.isEmpty() ? absoluteUrl : displayText); hyperlink.setOnAction(event -> { try { Desktop.getDesktop().browse(URI.create(absoluteUrl)); } catch (IOException e) { e.printStackTrace(); } }); setGraphic(hyperlink); } }
2. 为ListView设置单元格工厂
将自定义的LinkCell绑定到ListView,让列表使用该单元格渲染每个标签元素:
import javafx.scene.control.ListView; import org.jsoup.nodes.Element; // 初始化ListView ListView<Element> linkListView = new ListView<>(); // 设置单元格工厂 linkListView.setCellFactory(listView -> new LinkCell()); // 绑定SoupService的结果到ListView的数据源 SoupService soupService = new SoupService(); linkListView.itemsProperty().bind(soupService.valueProperty()); // 启动后台采集任务 soupService.start();
关键注意事项
- 相对链接处理:使用JSoup的
absUrl("href")替代attr("href"),能自动基于原网页的基准URL将相对路径转换为可直接访问的绝对链接。 - 单元格复用:必须在
updateItem()中处理empty或null的情况,清空单元格内容,防止旧数据残留。 - 线程安全:
Service的valueProperty会自动在JavaFX应用线程更新,直接绑定到ListView.itemsProperty()无需额外线程处理。
内容的提问来源于stack exchange,提问作者trashgod
相关产品推荐
相关产品推荐

