JLabel hyperlink to open browser at correct URL

拈花ヽ惹草 提交于 2019-12-05 01:44:02

Easy, just copy this method to your code with the right parameters. Don't forget to add the imports needed.

import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;


    private void goWebsite(JLabel website, final String url, String text) {
        website.setText("<html> Website : <a href=\"\">"+text+"</a></html>");
        website.setCursor(new Cursor(Cursor.HAND_CURSOR));
        website.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                    try {
                            Desktop.getDesktop().browse(new URI(url));
                    } catch (URISyntaxException | IOException ex) {
                            //It looks like there's a problem
                    }
            }
        });
    }
 public void mouseClicked(MouseEvent e) {
      if (e.getClickCount() > 0) {
          if (Desktop.isDesktopSupported()) {
                                try {
                    String osName = System.getProperty("os.name");
                    String urlPath = "http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html";

                    if (osName.startsWith("Windows"))
                        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + urlPath);
                    else {
                        String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
                        String browser = null;
                        for (int count = 0; count < browsers.length && browser == null; count++)
                            if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0)
                                browser = browsers[count];
                        Runtime.getRuntime().exec(new String[] { browser, urlPath });
                    }
                }
                catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Error in opening browser" + ":\n" + e.getLocalizedMessage());
                }
        }
      }
   }
});

Here is a code sample for what you need.

Your code worked fine for me running on a Mac with Safari as my default browser.

What browser are you using and what OS are you running on?

COD3BOY

This seems to be working, Here is a great alternative worth trying by McDowell, using a JButton,

public static void main(String[] args) throws URISyntaxException {
    final URI uri = new URI("http://java.sun.com");
    class OpenUrlAction implements ActionListener {
      @Override public void actionPerformed(ActionEvent e) {
        open(uri);
      }
    }
    JFrame frame = new JFrame("Links");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(100, 400);
    Container container = frame.getContentPane();
    container.setLayout(new GridBagLayout());
    JButton button = new JButton();
    button.setText("<HTML>Click the <FONT color=\"#000099\"><U>link</U></FONT>"
        + " to go to the Java website.</HTML>");
    button.setHorizontalAlignment(SwingConstants.LEFT);
    button.setBorderPainted(false);
    button.setOpaque(false);
    button.setBackground(Color.WHITE);
    button.setToolTipText(uri.toString());
    button.addActionListener(new OpenUrlAction());
    container.add(button);
    frame.setVisible(true);
  }

  private static void open(URI uri) {
    if (Desktop.isDesktopSupported()) {
      try {
        Desktop.getDesktop().browse(uri);
      } catch (IOException e) { /* TODO: error handling */ }
    } else { /* TODO: error handling */ }
  }

Found the problem: on Ubuntu 12.10 I have installed "libgnome2" and it is working perfectly now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!