java - JavaFx - 从字符串中提取 url 并使 url 可点击
问题描述
我尝试实施一些现有的解决方案,但对我没有帮助。从 API 接收到一个字符串“您可以访问网站:http://localhost:0000/stack_overflow/ ”。需要显示整个字符串。我想以这样的方式拆分字符串,使“ http://localhost:0000/stack_overflow/ ”部分成为超链接并可点击。
我尝试使用 TextFlow 并将文本拆分为文本和超链接,但是,当我使用“:”进行拆分时,所有的“:”都会破坏字符串。
String urlLink = "You can visit out website:http://localhost:0000/stack_overflow/";
TextFlow textFlow = new TextFlow();
ImageView imageView = new ImageView();
imageView.setImage(new Image(Resources.ICON));
String[] information = urlLink.split(":");
Text txtInfo = new Text(information[0]);
Hyperlink link = new Hyperlink(information[1]);
link.setOnAction(event -> {
try {
Runtime.getRuntime().exec("cmd.exe /c start iexplore " + link);
} catch (IOException e) {
e.printStackTrace();
}
});
textFlow = new TextFlow(txtInfo, link);
解决方案
String.split()
您可以使用允许您指定拆分中项目数量的限制的重载版本。(这几乎正是链接文档中表格第一行中的示例。)
String[] information = description.getCaption().split(":", 2);
要在文本中显示冒号,只需将其连接回:
Text txtInfo = new Text(information[0] + ":");
请注意,在系统浏览器中显示 URL 的更好的、独立于平台的方法是使用getHostServices().showDocument(...)
. 该getHostServices()
方法可从您的Application
实例中获得;有关如何向HostServices
应用程序的其他部分提供的详细信息,请参阅JavaFx 8:在浏览器中打开链接而不参考 Application。
String urlLink = "You can visit our website:http://localhost:0000/stack_overflow/";
TextFlow textFlow = new TextFlow();
String[] information = description.getCaption().split(":", 2);
Text txtInfo = new Text(information[0] + ":");
Hyperlink link = new Hyperlink(information[1]);
link.setOnAction(event -> getHostServices().showDocument(information[1]));
textFlow = new TextFlow(txtInfo, link);
推荐阅读
- database - CodeIgniter:没有 www 的服务器名称不会选择正确的数据库配置
- php - 使用 zoonman/linkedin-api-php-client 从 LinkedIn API V2 获取完整的 r_basicprofile 信息
- tensorflow - Keras 报告的准确性与 model.predict() 不符
- curl - 如何将 curl --use 标志转换为在邮递员中使用
- java - Spring Data JPA - 大规模更新不起作用
- java - Rxjava2:平面图使用
- express - Express app.get 不执行中间件功能
- mysql - 修改 SQL 查询以返回更多相似的结果
- server - C 中的套接字绑定错误(无法分配请求的地址)
- r - 运行 ANOVA 时出现“对比仅适用于因子”错误