首页 > 解决方案 > 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);

标签: javajavafxjava-8hyperlink

解决方案


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

推荐阅读