Подтвердить что ты не робот

Открыть ссылку в браузере с помощью кнопки java?

Как я могу открыть ссылку в браузере по умолчанию с нажатием кнопки по линиям

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        open("www.google.com"); // just what is the 'open' method?
    }
});

?

4b9b3361

Ответ 1

Используйте метод Desktop # browse (URI). Он открывает URI в браузере пользователя по умолчанию.

public static boolean openWebpage(URI uri) {
    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
        try {
            desktop.browse(uri);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}

public static boolean openWebpage(URL url) {
    try {
        return openWebpage(url.toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return false;
}

Ответ 2

public static void openWebpage(String urlString) {
    try {
        Desktop.getDesktop().browse(new URL(urlString).toURI());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Ответ 3

try {
    Desktop.getDesktop().browse(new URL("http://www.google.com").toURI());
} catch (Exception e) {}

Примечание: вы должны включить необходимые импорт из java.net

Ответ 4

Решение без рабочей среды BrowserLauncher2. Это решение более общее, как в Linux, Desktop не всегда доступен.

Самый длинный ответ отправлен на fooobar.com/questions/66952/...

Ответ 5

private void ButtonOpenWebActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try { 
         String url = "https://www.google.com";
         java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
       }
       catch (java.io.IOException e) {
           System.out.println(e.getMessage());
       }
    }    

Ответ 6

public static void openWebPage(String url) {
        try {
            Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
            if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
                desktop.browse(new URI(url));
            }
            throw new NullPointerException();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, url, "", JOptionPane.PLAIN_MESSAGE);
        }
    }

Ответ 7

Я знаю, что это старый вопрос, но иногда Desktop.getDesktop() выдает неожиданный сбой, как в Ubuntu 18.04. Поэтому я должен переписать свой код следующим образом:

public static void openURL(String domain)
{
    String url = "https://" + domain;
    Runtime rt = Runtime.getRuntime();
    try {
        if (MUtils.isWindows()) {
            rt.exec("rundll32 url.dll,FileProtocolHandler " + url).waitFor();
            Debug.log("Browser: " + url);
        } else if (MUtils.isMac()) {
            String[] cmd = {"open", url};
            rt.exec(cmd).waitFor();
            Debug.log("Browser: " + url);
        } else if (MUtils.isUnix()) {
            String[] cmd = {"xdg-open", url};
            rt.exec(cmd).waitFor();
            Debug.log("Browser: " + url);
        } else {
            try {
                throw new IllegalStateException();
            } catch (IllegalStateException e1) {
                MUtils.alertMessage(Lang.get("desktop.not.supported"), MainPn.getMainPn());
                e1.printStackTrace();
            }
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

public static boolean isWindows()
{
    return OS.contains("win");
}

public static boolean isMac()
{
    return OS.contains("mac");
}

public static boolean isUnix()
{
    return OS.contains("nix") || OS.contains("nux") || OS.indexOf("aix") > 0;
}

Затем мы можем вызвать этого помощника из экземпляра:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        MUtils.openURL("www.google.com"); // just what is the 'open' method?
    }
});

Ответ 8

Я не знаю, но я делаю код в Java! Чтобы доказать, смотрите ниже.

    public class variables {
      public static void main(String[] args) {
        System.out.println("This is printing a variable bellow!");
        string var = "This string is made of a variable!";
        System.out.println(var);
      }
    }

Это доказало это тебе? Если это не так, я делаю приложение!