当单击 JavaFX 中的超链接时,应在浏览器中打开相关 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24448002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:15:45  来源:igfitidea点击:

When Click on Hyperlinks in JavaFX ,a relevant URL should open in browser

javajavafxjavafx-2desktop-application

提问by Anish Sharma

I am developing an application in which I have some links added to the Listview and these links will keep on adding at runtime on some condition.So what I can't find is a way to how to open a url when clicking on a particular link.

我正在开发一个应用程序,其中我将一些链接添加到 Listview,并且这些链接将在运行时在某些条件下继续添加。所以我找不到一种在单击特定链接时如何打开 url 的方法.

This is the code for adding links into list view

这是将链接添加到列表视图的代码

    if(counter==1)
                {
                    Task task2 = new Task<Void>() {
                          @Override
                          public Void call() throws Exception {

                              Platform.runLater(new Runnable() {
                                public void run() {
                                     link=new Hyperlink(val);
                                    link.setStyle("-fx-border-style: none;");
                                    items.add(link);
                                    listview.setItems(items);



                                }
                              });


                            return null;

                          }
                        };
                        Thread th = new Thread(task2);
                        th.setDaemon(true);
                        th.start(); 
                        Thread.sleep(1000);


                }

I know I need to use something like this to open a url in browser when click on link

我知道当点击链接时我需要使用这样的东西在浏览器中打开一个网址

 getHostServices().showDocument(link.getText()); 

but I don't know how to listen/track the click event for different links

但我不知道如何监听/跟踪不同链接的点击事件

采纳答案by Patrick

I made a very small example Application for you,

我为您制作了一个非常小的示例应用程序,

import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ListList extends Application {

    final ListView listView = new ListView();
    @Override
    public void start(Stage primaryStage) {

        List<Hyperlink> links = new ArrayList<>();

        AnchorPane pane = new AnchorPane();
        VBox vBox = new VBox();
        final Hyperlink link = new Hyperlink("http://blog.professional-webworkx.de");
        Hyperlink link2= new Hyperlink("http://www.stackoverflow.com");

        links.add(link);
        links.add(link2);

        for(final Hyperlink hyperlink : links) {
            hyperlink.setOnAction(new EventHandler<ActionEvent>() {

                @Override
                public void handle(ActionEvent t) {
                    getHostServices().showDocument(hyperlink.getText());
                }
            });
        }

        listView.getItems().addAll(links);
        HBox hBox = new HBox();
        final TextField urlField = new TextField();
        Button b = new Button("Add Links");
        hBox.getChildren().addAll(b, urlField);

        b.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                addLink(urlField.getText().trim());
                urlField.clear();
            }
        });
        vBox.getChildren().add(hBox);
        vBox.getChildren().add(listView);
        pane.getChildren().add(vBox);
        Scene scene = new Scene(pane, 800, 600);
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

    private void addLink(final String url) {
        final Hyperlink link = new Hyperlink(url);
        link.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                getHostServices().showDocument(link.getText());
                //openBrowser(link.getText());
            }

        });
        listView.getItems().add(link);
    }

    private void openBrowser(final String url) {
        getHostServices().showDocument(url);
    }
}

If you enter a new URL in the TextField and click on the Button, the new Link will be added to your LinkList and will be displayed on the ListView. Everytime you add a new Link, the .setOnAction()Method is set with the right URL to open.

如果您在 TextField 中输入新 URL 并单击 Button,新链接将添加到您的 LinkList 并显示在 ListView 上。每次添加新链接时,.setOnAction()都会使用正确的 URL 设置方法以打开。

Maybe you can use this as starting point for further developing your app.

也许您可以将此作为进一步开发应用程序的起点。

Patrick

帕特里克

回答by Kaj Risberg

I put a Tooltip to the hyperlink and read the url from there, and seems to work. i.e.:

我在超链接上放了一个工具提示,并从那里读取了 url,似乎工作正常。IE:

Hyperlink hl = new Hyperlink(sometext);
hl.setTooltip(new Tooltip(theurlhere);
hl.setOnAction((ActionEvent event) -> {
    Hyperlink h = (Hyperlink) event.getTarget();
    String s = h.getTooltip().getText();
    getHostServices.showDocument(s);
    event.consume();
});

回答by kleopatra

Old question, old answer which is working fine - but has a slight smell: it's adding views (Hyperlinks) as data to the ListView.

老问题,老答案,工作正常 - 但有一点味道:它正在将视图(超链接)作为数据添加到 ListView。

The cleaner alternative is to add URLs as data and implement a custom cell that uses Hyperlinks to show (and allow interaction with) the URLs.

更简洁的替代方法是将 URL 添加为数据并实现使用超链接来显示(并允许与之交互)URL 的自定义单元格。

A quick code example:

一个快速的代码示例:

final ListView<URL> listView = new ListView<>();

@Override
public void start(Stage primaryStage) throws MalformedURLException {

    ObservableList<URL> urls = FXCollections.observableArrayList(
          new URL("http://blog.professional-webworkx.de"),
          new URL("http://www.stackoverflow.com")
            );

    listView.getItems().addAll(urls);
    listView.setCellFactory(c -> {
        ListCell<URL> cell = new ListCell<>() {
            private Hyperlink hyperlink;

            {
                hyperlink = new Hyperlink();
                hyperlink.setOnAction(e -> {
                    if (getItem() != null) {
                        getHostServices().showDocument(getItem().toString());
                    }
                });
                setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            }

            @Override
            protected void updateItem(URL item, boolean empty) {
                super.updateItem(item, empty);
                if (item != null && !empty) {
                    hyperlink.setText(item.toString());
                    setGraphic(hyperlink);
                } else {
                    setGraphic(null);
                }
            }

        };
        return cell;
    });
   // ... 
}