【问题标题】:JLabel hyperlink to open browser at correct URLJLabel 超链接以正确的 URL 打开浏览器
【发布时间】:2012-01-29 23:01:33
【问题描述】:

我需要使用 Java Swing 创建一个可单击的标签,并且能够在桌面上打开默认浏览器并将其重定向到特定的 url。我的代码能够打开浏览器,但不能将其重定向到正确的 url(已加载默认主页)。我的测试代码:

 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 import java.io.IOException;
 import java.net.*;

 public class LinkTest extends JFrame {

 public LinkTest() {
 JPanel p = new JPanel();

 JLabel link = new JLabel("Click here");
 link.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
 link.addMouseListener(new MouseAdapter() {
   public void mouseClicked(MouseEvent e) {
      if (e.getClickCount() > 0) {
          if (Desktop.isDesktopSupported()) {
                Desktop desktop = Desktop.getDesktop();
                try {
                    URI uri = new URI("http://www.bbc.co.uk");
                    desktop.browse(uri);
                } catch (IOException ex) {
                    ex.printStackTrace();
                } catch (URISyntaxException ex) {
                    ex.printStackTrace();
                }
        }
      }
   }
});
p.add(link);
getContentPane().add(BorderLayout.NORTH, p);
 }

 public static void main(String[] args) {
  LinkTest linkTest = new LinkTest();
  linkTest.setSize(640,100);
  linkTest.show();
 }
}

如何使用 Java Swing 打开默认浏览器并重定向到正确的 URL?

【问题讨论】:

  • 什么操作系统和浏览器?有什么例外吗?
  • 它在 Win 7 上运行,使用最新模型 1.6 JRE & FF 作为默认浏览器。
  • 对不起,我忘了提到操作系统/浏览器:Ubuntu 11.10 + Chrome 16 + Java 6
  • 也为我工作(Windows 7 64 位 + Firefox 8 + JRE 6)。我也对这个东西很感兴趣,所以我也想尝试让它在任何地方都能工作。

标签: java swing browser hyperlink jlabel


【解决方案1】:

很简单,只需将此方法复制到带有正确参数的代码中即可。不要忘记添加所需的导入。

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

【讨论】:

    【解决方案2】:
     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());
                    }
            }
          }
       }
    });
    

    【讨论】:

      【解决方案3】:

      Here 是您需要的代码示例。

      【讨论】:

        【解决方案4】:

        你的代码在我的 Mac 上运行良好,Safari 作为我的默认浏览器。

        您使用的是什么浏览器以及运行的是什么操作系统?

        【讨论】:

        • Ubuntu 11.10 + Chrome 16 + Java 6
        【解决方案5】:

        这似乎奏效了,Here 是 McDowell 尝试使用 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 */ }
          }
        

        【讨论】:

          【解决方案6】:

          发现问题:在 Ubuntu 12.10 上,我安装了“libgnome2”,现在可以正常工作了。

          【讨论】:

            猜你喜欢
            • 2023-03-03
            • 2012-12-15
            • 1970-01-01
            • 2021-06-26
            • 1970-01-01
            • 2018-06-29
            • 2012-02-21
            • 1970-01-01
            • 2014-08-18
            相关资源
            最近更新 更多