如何在JLabel中添加超链接?

时间:2022-11-15 22:12:56

Which is the best way to add a hyperlink in jLabel? I can get the view using html tags, but how to open the browser when the user clicks on it?

在jLabel中添加超链接的最好方法是什么?我可以使用html标记获取视图,但是当用户单击它时如何打开浏览器呢?

12 个解决方案

#1


89  

You can do this using a JLabel, but an alternative would be to style a JButton. That way, you don't have to worry about accessibility and can just fire events using an ActionListener.

您可以使用JLabel来实现这一点,但是另一种选择是样式化JButton。这样,您就不必担心可访问性,只需使用ActionListener就可以触发事件。

  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 */ }
  }

#2


27  

I'd like to offer yet another solution. It's similar to the already proposed ones as it uses HTML-code in a JLabel, and registers a MouseListener on it, but it also displays a HandCursor when you move the mouse over the link, so the look&feel is just like what most users would expect. If browsing is not supported by the platform, no blue, underlined HTML-link is created that could mislead the user. Instead, the link is just presented as plain text. This could be combined with the SwingLink class proposed by @dimo414.

我想再提供一个解决方案。它与已经提出的方法类似,因为它在JLabel中使用html代码,并在它上面注册一个MouseListener,但是当您在链接上移动鼠标时,它也会显示一个HandCursor,因此look&feel就像大多数用户所期望的那样。如果平台不支持浏览,那么就不会创建蓝色的、下划线的html链接,这会误导用户。相反,该链接只是作为纯文本呈现。这可以与@dimo414提出的SwingLink类结合起来。

public class JLabelLink extends JFrame {

private static final String LABEL_TEXT = "For further information visit:";
private static final String A_VALID_LINK = "http://*.com";
private static final String A_HREF = "<a href=\"";
private static final String HREF_CLOSED = "\">";
private static final String HREF_END = "</a>";
private static final String HTML = "<html>";
private static final String HTML_END = "</html>";

public JLabelLink() {
    setTitle("HTML link via a JLabel");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    Container contentPane = getContentPane();
    contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));

    JLabel label = new JLabel(LABEL_TEXT);
    contentPane.add(label);

    label = new JLabel(A_VALID_LINK);
    contentPane.add(label);
    if (isBrowsingSupported()) {
        makeLinkable(label, new LinkMouseListener());
    }

    pack();
}

private static void makeLinkable(JLabel c, MouseListener ml) {
    assert ml != null;
    c.setText(htmlIfy(linkIfy(c.getText())));
    c.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
    c.addMouseListener(ml);
}

private static boolean isBrowsingSupported() {
    if (!Desktop.isDesktopSupported()) {
        return false;
    }
    boolean result = false;
    Desktop desktop = java.awt.Desktop.getDesktop();
    if (desktop.isSupported(Desktop.Action.BROWSE)) {
        result = true;
    }
    return result;

}

private static class LinkMouseListener extends MouseAdapter {

    @Override
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        JLabel l = (JLabel) evt.getSource();
        try {
            URI uri = new java.net.URI(JLabelLink.getPlainLink(l.getText()));
            (new LinkRunner(uri)).execute();
        } catch (URISyntaxException use) {
            throw new AssertionError(use + ": " + l.getText()); //NOI18N
        }
    }
}

private static class LinkRunner extends SwingWorker<Void, Void> {

    private final URI uri;

    private LinkRunner(URI u) {
        if (u == null) {
            throw new NullPointerException();
        }
        uri = u;
    }

    @Override
    protected Void doInBackground() throws Exception {
        Desktop desktop = java.awt.Desktop.getDesktop();
        desktop.browse(uri);
        return null;
    }

    @Override
    protected void done() {
        try {
            get();
        } catch (ExecutionException ee) {
            handleException(uri, ee);
        } catch (InterruptedException ie) {
            handleException(uri, ie);
        }
    }

    private static void handleException(URI u, Exception e) {
        JOptionPane.showMessageDialog(null, "Sorry, a problem occurred while trying to open this link in your system's standard browser.", "A problem occured", JOptionPane.ERROR_MESSAGE);
    }
}

private static String getPlainLink(String s) {
    return s.substring(s.indexOf(A_HREF) + A_HREF.length(), s.indexOf(HREF_CLOSED));
}

//WARNING
//This method requires that s is a plain string that requires
//no further escaping
private static String linkIfy(String s) {
    return A_HREF.concat(s).concat(HREF_CLOSED).concat(s).concat(HREF_END);
}

//WARNING
//This method requires that s is a plain string that requires
//no further escaping
private static String htmlIfy(String s) {
    return HTML.concat(s).concat(HTML_END);
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            new JLabelLink().setVisible(true);
        }
    });
}
}

#3


16  

I wrote an article on how to set a hyperlink or a mailto on a jLabel.

我写了一篇关于如何在jLabel上设置超链接或mailto的文章。

So just try it :

所以试试吧:

I think that's exactly what you're searching for.

我认为这正是你想要的。

Here's the complete code example :

下面是完整的代码示例:

/**
 * Example of a jLabel Hyperlink and a jLabel Mailto
 */

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;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author ibrabelware
 */
public class JLabelLink extends JFrame {
    private JPanel pan;
    private JLabel contact;
        private JLabel website;
    /**
     * Creates new form JLabelLink
     */
    public JLabelLink() {
        this.setTitle("jLabelLinkExample");
        this.setSize(300, 100);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);

        pan = new JPanel();
        contact = new JLabel();
        website = new JLabel();

        contact.setText("<html> contact : <a href=\"\">YourEmailAddress@gmail.com</a></html>");
        contact.setCursor(new Cursor(Cursor.HAND_CURSOR));

        website.setText("<html> Website : <a href=\"\">http://www.google.com/</a></html>");
        website.setCursor(new Cursor(Cursor.HAND_CURSOR));

    pan.add(contact);
    pan.add(website);
        this.setContentPane(pan);
        this.setVisible(true);
        sendMail(contact);
        goWebsite(website);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Create and display the form
         */
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JLabelLink().setVisible(true);
            }
        });
    }

    private void goWebsite(JLabel website) {
        website.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().browse(new URI("http://www.google.com/webhp?nomo=1&hl=fr"));
                } catch (URISyntaxException | IOException ex) {
                    //It looks like there's a problem
                }
            }
        });
    }

    private void sendMail(JLabel contact) {
        contact.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().mail(new URI("mailto:YourEmailAddress@gmail.com?subject=TEST"));
                } catch (URISyntaxException | IOException ex) {
                    //It looks like there's a problem
                }
            }
        });
    }
}

#4


14  

Maybe use JXHyperlink from SwingX instead. It extends JButton. Some useful links:

也许可以使用SwingX中的JXHyperlink。它扩展了JButton。一些有用的链接:

#5


13  

Update I've tidied up the SwingLink class further and added more features; an up-to-date copy of it can be found here: https://bitbucket.org/dimo414/jgrep/src/tip/src/grep/SwingLink.java

更新我已经整理了SwingLink类,并添加了更多的特性;可以在这里找到它的最新副本:https://bitbucket.org/dimo414/ jgrep/src/src/grep/swinglink.java。


@McDowell's answer is great, but there's several things that could be improved upon. Notably text other than the hyperlink is clickable and it still looks like a button even though some of the styling has been changed/hidden. While accessibility is important, a coherent UI is as well.

@McDowell的回答很好,但是有几件事是可以改进的。值得注意的是,除了超链接之外的文本是可点击的,而且它看起来仍然像一个按钮,尽管有些样式已经被改变/隐藏了。虽然可访问性很重要,但一个连贯的UI也很重要。

So I put together a class extending JLabel based on McDowell's code. It's self-contained, handles errors properly, and feels more like a link:

因此,我将基于McDowell代码的JLabel扩展到一个类中。它是独立的,正确处理错误,感觉更像一个链接:

public class SwingLink extends JLabel {
  private static final long serialVersionUID = 8273875024682878518L;
  private String text;
  private URI uri;

  public SwingLink(String text, URI uri){
    super();
    setup(text,uri);
  }

  public SwingLink(String text, String uri){
    super();
    setup(text,URI.create(uri));
  }

  public void setup(String t, URI u){
    text = t;
    uri = u;
    setText(text);
    setToolTipText(uri.toString());
    addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        open(uri);
      }
      public void mouseEntered(MouseEvent e) {
        setText(text,false);
      }
      public void mouseExited(MouseEvent e) {
        setText(text,true);
      }
    });
  }

  @Override
  public void setText(String text){
    setText(text,true);
  }

  public void setText(String text, boolean ul){
    String link = ul ? "<u>"+text+"</u>" : text;
    super.setText("<html><span style=\"color: #000099;\">"+
    link+"</span></html>");
    this.text = text;
  }

  public String getRawText(){
    return text;
  }

  private static void open(URI uri) {
    if (Desktop.isDesktopSupported()) {
      Desktop desktop = Desktop.getDesktop();
      try {
        desktop.browse(uri);
      } catch (IOException e) {
        JOptionPane.showMessageDialog(null,
            "Failed to launch the link, your computer is likely misconfigured.",
            "Cannot Launch Link",JOptionPane.WARNING_MESSAGE);
      }
    } else {
      JOptionPane.showMessageDialog(null,
          "Java is not able to launch links on your computer.",
          "Cannot Launch Link", JOptionPane.WARNING_MESSAGE);
    }
  }
}

You could also, for instance, change the link color to purple after being clicked, if that seemed useful. It's all self contained, you simply call:

例如,您还可以在单击后将链接颜色更改为紫色,如果这看起来很有用的话。这一切都是自我控制的,你只要打个电话:

SwingLink link = new SwingLink("Java", "http://java.sun.com");
mainPanel.add(link);

#6


10  

You might try using a JEditorPane instead of a JLabel. This understands basic HTML and will send a HyperlinkEvent event to the HyperlinkListener you register with the JEditPane.

您可以尝试使用JEditorPane而不是JLabel。这将理解基本的HTML,并将向您在JEditPane注册的超链接侦听器发送一个超链接事件。

#7


4  

If <a href="link"> doesn't work, then:

如果不工作,则:

  1. Create a JLabel and add a MouseListener (decorate the label to look like a hyperlink)
  2. 创建一个JLabel并添加一个MouseListener(将标签装饰成一个超链接)
  3. Implement mouseClicked() event
  4. 实现mouseClicked()事件
  5. In the implementation of mouseClicked() event, perform your action
  6. 在mouseClicked()事件的实现中,执行您的操作。

Have a look at java.awt.Desktop API for opening a link using the default browser (this API is available only from Java6).

看看java.awt。使用默认浏览器打开链接的桌面API(此API仅从Java6可用)。

#8


4  

I know I'm kinda late to the party but I made a little method others might find cool/useful.

我知道我有点晚了,但我做了一些方法,其他人可能觉得很酷/有用。

public static JLabel linkify(final String text, String URL, String toolTip)
{
    URI temp = null;
    try
    {
        temp = new URI(URL);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    final URI uri = temp;
    final JLabel link = new JLabel();
    link.setText("<HTML><FONT color=\"#000099\">"+text+"</FONT></HTML>");
    if(!toolTip.equals(""))
        link.setToolTipText(toolTip);
    link.setCursor(new Cursor(Cursor.HAND_CURSOR));
    link.addMouseListener(new MouseListener()
    {
        public void mouseExited(MouseEvent arg0)
        {
            link.setText("<HTML><FONT color=\"#000099\">"+text+"</FONT></HTML>");
        }

        public void mouseEntered(MouseEvent arg0)
        {
            link.setText("<HTML><FONT color=\"#000099\"><U>"+text+"</U></FONT></HTML>");
        }

        public void mouseClicked(MouseEvent arg0)
        {
            if (Desktop.isDesktopSupported())
            {
                try
                {
                    Desktop.getDesktop().browse(uri);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
            else
            {
                JOptionPane pane = new JOptionPane("Could not open link.");
                JDialog dialog = pane.createDialog(new JFrame(), "");
                dialog.setVisible(true);
            }
        }

        public void mousePressed(MouseEvent e)
        {
        }

        public void mouseReleased(MouseEvent e)
        {
        }
    });
    return link;
}

It'll give you a JLabel that acts like a proper link.

它会给你一个JLabel,它就像一个正确的链接。

In action:

在行动:

public static void main(String[] args)
{
    JFrame frame = new JFrame("Linkify Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 100);
    frame.setLocationRelativeTo(null);
    Container container = frame.getContentPane();
    container.setLayout(new GridBagLayout());
    container.add(new JLabel("Click "));
    container.add(linkify("this", "http://facebook.com", "Facebook"));
    container.add(new JLabel(" link to open Facebook."));
    frame.setVisible(true);
}

If you'd like no tooltip just send a null.

如果你不喜欢工具提示,那就发送一个空。

Hope someone finds this useful! (If you do, be sure to let me know, I'd be happy to hear.)

希望有人发现这有用!(如果你这样做了,一定要告诉我,我很乐意听。)

#9


4  

Use a JEditorPane with a HyperlinkListener.

使用一个具有超链接监听器的JEditorPane。

#10


2  

Just put window.open(website url), it works every time.

把窗口。打开(网站url),它每次都有效。

#11


1  

The following code requires JHyperLink to be added to your build path.

下面的代码要求将JHyperLink添加到您的构建路径中。

JHyperlink * = new JHyperlink("Click HERE!",
                "https://www.*.com/");

JComponent[] messageComponents = new JComponent[] { * };

JOptionPane.showMessageDialog(null, messageComponents, "*",
                JOptionPane.PLAIN_MESSAGE);

Note that you can fill the JComponent array with more Swing components.

注意,您可以使用更多Swing组件来填充JComponent数组。

Result:

结果:

如何在JLabel中添加超链接?

#12


1  

You can use this under an

你可以用这个。

actionListener ->  Runtime.getRuntime().exec("cmd.exe /c start chrome www.google.com")`

or if you want to use Internet Explorer or Firefox replace chrome with iexplore or firefox

或者如果你想用ie或者Firefox来代替chrome浏览器或者火狐浏览器。

#1


89  

You can do this using a JLabel, but an alternative would be to style a JButton. That way, you don't have to worry about accessibility and can just fire events using an ActionListener.

您可以使用JLabel来实现这一点,但是另一种选择是样式化JButton。这样,您就不必担心可访问性,只需使用ActionListener就可以触发事件。

  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 */ }
  }

#2


27  

I'd like to offer yet another solution. It's similar to the already proposed ones as it uses HTML-code in a JLabel, and registers a MouseListener on it, but it also displays a HandCursor when you move the mouse over the link, so the look&feel is just like what most users would expect. If browsing is not supported by the platform, no blue, underlined HTML-link is created that could mislead the user. Instead, the link is just presented as plain text. This could be combined with the SwingLink class proposed by @dimo414.

我想再提供一个解决方案。它与已经提出的方法类似,因为它在JLabel中使用html代码,并在它上面注册一个MouseListener,但是当您在链接上移动鼠标时,它也会显示一个HandCursor,因此look&feel就像大多数用户所期望的那样。如果平台不支持浏览,那么就不会创建蓝色的、下划线的html链接,这会误导用户。相反,该链接只是作为纯文本呈现。这可以与@dimo414提出的SwingLink类结合起来。

public class JLabelLink extends JFrame {

private static final String LABEL_TEXT = "For further information visit:";
private static final String A_VALID_LINK = "http://*.com";
private static final String A_HREF = "<a href=\"";
private static final String HREF_CLOSED = "\">";
private static final String HREF_END = "</a>";
private static final String HTML = "<html>";
private static final String HTML_END = "</html>";

public JLabelLink() {
    setTitle("HTML link via a JLabel");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    Container contentPane = getContentPane();
    contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));

    JLabel label = new JLabel(LABEL_TEXT);
    contentPane.add(label);

    label = new JLabel(A_VALID_LINK);
    contentPane.add(label);
    if (isBrowsingSupported()) {
        makeLinkable(label, new LinkMouseListener());
    }

    pack();
}

private static void makeLinkable(JLabel c, MouseListener ml) {
    assert ml != null;
    c.setText(htmlIfy(linkIfy(c.getText())));
    c.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
    c.addMouseListener(ml);
}

private static boolean isBrowsingSupported() {
    if (!Desktop.isDesktopSupported()) {
        return false;
    }
    boolean result = false;
    Desktop desktop = java.awt.Desktop.getDesktop();
    if (desktop.isSupported(Desktop.Action.BROWSE)) {
        result = true;
    }
    return result;

}

private static class LinkMouseListener extends MouseAdapter {

    @Override
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        JLabel l = (JLabel) evt.getSource();
        try {
            URI uri = new java.net.URI(JLabelLink.getPlainLink(l.getText()));
            (new LinkRunner(uri)).execute();
        } catch (URISyntaxException use) {
            throw new AssertionError(use + ": " + l.getText()); //NOI18N
        }
    }
}

private static class LinkRunner extends SwingWorker<Void, Void> {

    private final URI uri;

    private LinkRunner(URI u) {
        if (u == null) {
            throw new NullPointerException();
        }
        uri = u;
    }

    @Override
    protected Void doInBackground() throws Exception {
        Desktop desktop = java.awt.Desktop.getDesktop();
        desktop.browse(uri);
        return null;
    }

    @Override
    protected void done() {
        try {
            get();
        } catch (ExecutionException ee) {
            handleException(uri, ee);
        } catch (InterruptedException ie) {
            handleException(uri, ie);
        }
    }

    private static void handleException(URI u, Exception e) {
        JOptionPane.showMessageDialog(null, "Sorry, a problem occurred while trying to open this link in your system's standard browser.", "A problem occured", JOptionPane.ERROR_MESSAGE);
    }
}

private static String getPlainLink(String s) {
    return s.substring(s.indexOf(A_HREF) + A_HREF.length(), s.indexOf(HREF_CLOSED));
}

//WARNING
//This method requires that s is a plain string that requires
//no further escaping
private static String linkIfy(String s) {
    return A_HREF.concat(s).concat(HREF_CLOSED).concat(s).concat(HREF_END);
}

//WARNING
//This method requires that s is a plain string that requires
//no further escaping
private static String htmlIfy(String s) {
    return HTML.concat(s).concat(HTML_END);
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            new JLabelLink().setVisible(true);
        }
    });
}
}

#3


16  

I wrote an article on how to set a hyperlink or a mailto on a jLabel.

我写了一篇关于如何在jLabel上设置超链接或mailto的文章。

So just try it :

所以试试吧:

I think that's exactly what you're searching for.

我认为这正是你想要的。

Here's the complete code example :

下面是完整的代码示例:

/**
 * Example of a jLabel Hyperlink and a jLabel Mailto
 */

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;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author ibrabelware
 */
public class JLabelLink extends JFrame {
    private JPanel pan;
    private JLabel contact;
        private JLabel website;
    /**
     * Creates new form JLabelLink
     */
    public JLabelLink() {
        this.setTitle("jLabelLinkExample");
        this.setSize(300, 100);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);

        pan = new JPanel();
        contact = new JLabel();
        website = new JLabel();

        contact.setText("<html> contact : <a href=\"\">YourEmailAddress@gmail.com</a></html>");
        contact.setCursor(new Cursor(Cursor.HAND_CURSOR));

        website.setText("<html> Website : <a href=\"\">http://www.google.com/</a></html>");
        website.setCursor(new Cursor(Cursor.HAND_CURSOR));

    pan.add(contact);
    pan.add(website);
        this.setContentPane(pan);
        this.setVisible(true);
        sendMail(contact);
        goWebsite(website);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Create and display the form
         */
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JLabelLink().setVisible(true);
            }
        });
    }

    private void goWebsite(JLabel website) {
        website.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().browse(new URI("http://www.google.com/webhp?nomo=1&hl=fr"));
                } catch (URISyntaxException | IOException ex) {
                    //It looks like there's a problem
                }
            }
        });
    }

    private void sendMail(JLabel contact) {
        contact.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().mail(new URI("mailto:YourEmailAddress@gmail.com?subject=TEST"));
                } catch (URISyntaxException | IOException ex) {
                    //It looks like there's a problem
                }
            }
        });
    }
}

#4


14  

Maybe use JXHyperlink from SwingX instead. It extends JButton. Some useful links:

也许可以使用SwingX中的JXHyperlink。它扩展了JButton。一些有用的链接:

#5


13  

Update I've tidied up the SwingLink class further and added more features; an up-to-date copy of it can be found here: https://bitbucket.org/dimo414/jgrep/src/tip/src/grep/SwingLink.java

更新我已经整理了SwingLink类,并添加了更多的特性;可以在这里找到它的最新副本:https://bitbucket.org/dimo414/ jgrep/src/src/grep/swinglink.java。


@McDowell's answer is great, but there's several things that could be improved upon. Notably text other than the hyperlink is clickable and it still looks like a button even though some of the styling has been changed/hidden. While accessibility is important, a coherent UI is as well.

@McDowell的回答很好,但是有几件事是可以改进的。值得注意的是,除了超链接之外的文本是可点击的,而且它看起来仍然像一个按钮,尽管有些样式已经被改变/隐藏了。虽然可访问性很重要,但一个连贯的UI也很重要。

So I put together a class extending JLabel based on McDowell's code. It's self-contained, handles errors properly, and feels more like a link:

因此,我将基于McDowell代码的JLabel扩展到一个类中。它是独立的,正确处理错误,感觉更像一个链接:

public class SwingLink extends JLabel {
  private static final long serialVersionUID = 8273875024682878518L;
  private String text;
  private URI uri;

  public SwingLink(String text, URI uri){
    super();
    setup(text,uri);
  }

  public SwingLink(String text, String uri){
    super();
    setup(text,URI.create(uri));
  }

  public void setup(String t, URI u){
    text = t;
    uri = u;
    setText(text);
    setToolTipText(uri.toString());
    addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        open(uri);
      }
      public void mouseEntered(MouseEvent e) {
        setText(text,false);
      }
      public void mouseExited(MouseEvent e) {
        setText(text,true);
      }
    });
  }

  @Override
  public void setText(String text){
    setText(text,true);
  }

  public void setText(String text, boolean ul){
    String link = ul ? "<u>"+text+"</u>" : text;
    super.setText("<html><span style=\"color: #000099;\">"+
    link+"</span></html>");
    this.text = text;
  }

  public String getRawText(){
    return text;
  }

  private static void open(URI uri) {
    if (Desktop.isDesktopSupported()) {
      Desktop desktop = Desktop.getDesktop();
      try {
        desktop.browse(uri);
      } catch (IOException e) {
        JOptionPane.showMessageDialog(null,
            "Failed to launch the link, your computer is likely misconfigured.",
            "Cannot Launch Link",JOptionPane.WARNING_MESSAGE);
      }
    } else {
      JOptionPane.showMessageDialog(null,
          "Java is not able to launch links on your computer.",
          "Cannot Launch Link", JOptionPane.WARNING_MESSAGE);
    }
  }
}

You could also, for instance, change the link color to purple after being clicked, if that seemed useful. It's all self contained, you simply call:

例如,您还可以在单击后将链接颜色更改为紫色,如果这看起来很有用的话。这一切都是自我控制的,你只要打个电话:

SwingLink link = new SwingLink("Java", "http://java.sun.com");
mainPanel.add(link);

#6


10  

You might try using a JEditorPane instead of a JLabel. This understands basic HTML and will send a HyperlinkEvent event to the HyperlinkListener you register with the JEditPane.

您可以尝试使用JEditorPane而不是JLabel。这将理解基本的HTML,并将向您在JEditPane注册的超链接侦听器发送一个超链接事件。

#7


4  

If <a href="link"> doesn't work, then:

如果不工作,则:

  1. Create a JLabel and add a MouseListener (decorate the label to look like a hyperlink)
  2. 创建一个JLabel并添加一个MouseListener(将标签装饰成一个超链接)
  3. Implement mouseClicked() event
  4. 实现mouseClicked()事件
  5. In the implementation of mouseClicked() event, perform your action
  6. 在mouseClicked()事件的实现中,执行您的操作。

Have a look at java.awt.Desktop API for opening a link using the default browser (this API is available only from Java6).

看看java.awt。使用默认浏览器打开链接的桌面API(此API仅从Java6可用)。

#8


4  

I know I'm kinda late to the party but I made a little method others might find cool/useful.

我知道我有点晚了,但我做了一些方法,其他人可能觉得很酷/有用。

public static JLabel linkify(final String text, String URL, String toolTip)
{
    URI temp = null;
    try
    {
        temp = new URI(URL);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    final URI uri = temp;
    final JLabel link = new JLabel();
    link.setText("<HTML><FONT color=\"#000099\">"+text+"</FONT></HTML>");
    if(!toolTip.equals(""))
        link.setToolTipText(toolTip);
    link.setCursor(new Cursor(Cursor.HAND_CURSOR));
    link.addMouseListener(new MouseListener()
    {
        public void mouseExited(MouseEvent arg0)
        {
            link.setText("<HTML><FONT color=\"#000099\">"+text+"</FONT></HTML>");
        }

        public void mouseEntered(MouseEvent arg0)
        {
            link.setText("<HTML><FONT color=\"#000099\"><U>"+text+"</U></FONT></HTML>");
        }

        public void mouseClicked(MouseEvent arg0)
        {
            if (Desktop.isDesktopSupported())
            {
                try
                {
                    Desktop.getDesktop().browse(uri);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
            else
            {
                JOptionPane pane = new JOptionPane("Could not open link.");
                JDialog dialog = pane.createDialog(new JFrame(), "");
                dialog.setVisible(true);
            }
        }

        public void mousePressed(MouseEvent e)
        {
        }

        public void mouseReleased(MouseEvent e)
        {
        }
    });
    return link;
}

It'll give you a JLabel that acts like a proper link.

它会给你一个JLabel,它就像一个正确的链接。

In action:

在行动:

public static void main(String[] args)
{
    JFrame frame = new JFrame("Linkify Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 100);
    frame.setLocationRelativeTo(null);
    Container container = frame.getContentPane();
    container.setLayout(new GridBagLayout());
    container.add(new JLabel("Click "));
    container.add(linkify("this", "http://facebook.com", "Facebook"));
    container.add(new JLabel(" link to open Facebook."));
    frame.setVisible(true);
}

If you'd like no tooltip just send a null.

如果你不喜欢工具提示,那就发送一个空。

Hope someone finds this useful! (If you do, be sure to let me know, I'd be happy to hear.)

希望有人发现这有用!(如果你这样做了,一定要告诉我,我很乐意听。)

#9


4  

Use a JEditorPane with a HyperlinkListener.

使用一个具有超链接监听器的JEditorPane。

#10


2  

Just put window.open(website url), it works every time.

把窗口。打开(网站url),它每次都有效。

#11


1  

The following code requires JHyperLink to be added to your build path.

下面的代码要求将JHyperLink添加到您的构建路径中。

JHyperlink * = new JHyperlink("Click HERE!",
                "https://www.*.com/");

JComponent[] messageComponents = new JComponent[] { * };

JOptionPane.showMessageDialog(null, messageComponents, "*",
                JOptionPane.PLAIN_MESSAGE);

Note that you can fill the JComponent array with more Swing components.

注意,您可以使用更多Swing组件来填充JComponent数组。

Result:

结果:

如何在JLabel中添加超链接?

#12


1  

You can use this under an

你可以用这个。

actionListener ->  Runtime.getRuntime().exec("cmd.exe /c start chrome www.google.com")`

or if you want to use Internet Explorer or Firefox replace chrome with iexplore or firefox

或者如果你想用ie或者Firefox来代替chrome浏览器或者火狐浏览器。