简体   繁体   English

简化URL按钮

[英]Simplifying a URL button

I am trying to add a link to an "about" window in an application that will link to my Github. 我正在尝试将链接添加到将链接到我的Github的应用程序中的“关于”窗口。 I sort of know the process, however, it seems to complicated for what it does, with all the error catching I have to put in. As I am certain the URI syntax is correct, is there any way to skip this catch? 我有点知道该过程,但是它的功能似乎很复杂,我必须放入所有错误捕获功能。我确定URI语法正确,是否有任何方法可以跳过此捕获操作? This variable stays final, and unless the syntax of resource location changes, it should be OK 该变量保持最终状态,除非资源位置的语法更改,否则应为OK。

Code: 码:

        //TODO: Simplify?
        String gitLocation = "https://github.com/DanubeRS";
        try {
            final URI gitUri = new URI(gitLocation);

            //Add the github button action (link to site)
            githubButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        Desktop.getDesktop().browse(gitUri.resolve(gitUri));  //Try to open URL
                    } catch (IOException e1) {
                        //URI unresolvable
                        e1.printStackTrace();
                    }
                }
            });
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

You could use the convenience method URI.create(String str) , which wraps the URISyntaxException with an IllegalArgumentException . 您可以使用便捷方法URI.create(String str) ,该方法将URISyntaxExceptionIllegalArgumentException包装在一起。 From the JavaDoc: 从JavaDoc:

This method is provided for use in situations where it is known that the given string is a legal URI, for example for URI constants declared within in a program, and so it would be considered a programming error for the string not to parse as such. 提供此方法是在已知给定字符串是合法URI的情况下使用,例如,对于程序中声明的URI常量,因此将其视为无法解析为字符串的编程错误。 The constructors, which throw URISyntaxException directly, should be used situations where a URI is being constructed from user input or from some other source that may be prone to errors. 直接从用户输入或从其他易于出错的来源构造URI的情况下,应使用直接抛出URISyntaxException的构造函数。

The IOException thrown from Desktop.browse() indicates that there's no default browser set up. Desktop.browse()引发的IOException表示未设置默认浏览器。 You should probably handle that gracefully by notifying the user. 您可能应该通过通知用户来妥善处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM