2009-02-09 194 views
81

這是在jLabel中添加超鏈接的最佳方式?我可以使用html標籤獲取視圖,但是當用戶點擊它時如何打開瀏覽器?如何在JLabel中添加超鏈接

+0

[HTTP更換chrome: //sourceforge.net/projects/jhyperlink/](http://sourceforge.net/projects/jhyperlink/) – dm76 2011-12-15 10:50:27

+0

簡單的解決方案,你可以在這裏找到:[解決方案](http://stackoverflow.com/questions/8669350/jlabel-hyperlink-to-open-browser-at-correct-url) – 2016-12-03 10:07:56

回答

87

您可以在此使用JLabel,但更好的方法將是風格JButton做。這樣,您不必擔心accessibility,只需使用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 */ } 
    } 
+0

這是如此的有益和酷,我總是想知道如何做到這一點,謝謝百萬:) – 2012-11-14 03:56:18

+1

+1或者使用`JTextField`如[本答案](http://stackoverflow.com/a/13871898/418556)所示。 – 2012-12-31 11:48:55

+0

+1偉大的工作完成的男人:) – saikosen 2013-09-17 13:32:01

4

如果< A HREF = 「鏈接」 >不起作用,那麼:

  1. 創建一個JLabel和添加的MouseListener(裝飾標籤看起來像一個超鏈接)
  2. 實施mouseClicked()事件
  3. 在的mouseClicked()事件的執行,執行你的行動

看一看java.awt.Desktop API爲openin g使用默認瀏覽器的鏈接(此API僅適用於Java6)。

13

更新我已經收拾了SwingLink類進一步,並添加更多的功能;它的一個跟上時代的副本可以在這裏找到:https://bitbucket.org/dimo414/jgrep/src/tip/src/grep/SwingLink.java


@麥克道爾的回答是偉大的,但有幾件事情是可以改進的。值得注意的是,超鏈接以外的文本是可點擊的,並且它仍然看起來像一個按鈕,即使某些樣式已被更改/隱藏。雖然可訪問性很重要,但一致的用戶界面也是如此。

因此,我將基於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); 
    } 
    } 
} 

你也可以,例如,鏈接顏色改爲紫色被點擊之後,如果這似乎是有用的。這是全部自包含的,你只需調用:

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

你可以嘗試使用JEditorPane而不是JLabel。這理解了基本的HTML,並將HyperlinkEvent事件發送到您在JEditPane中註冊的HyperlinkListener。

27

我想提供另一種解決方案。它與已經提出的類似,因爲它使用JLabel中的HTML代碼,並且在其上註冊了MouseListener,但是當您將鼠標移動到鏈接上時它也顯示一個HandCursor,所以外觀&的感覺就像大多數用戶會期待。如果平臺不支持瀏覽,則不會創建可能誤導用戶的藍色下劃線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://stackoverflow.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); 
     } 
    }); 
} 
} 
16

我寫了一篇關於如何在jLabel上設置超鏈接或mailto的文章。

所以只是嘗試it

我認爲這是您要搜索什麼的。

下面是完整的代碼示例:

/** 
* 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=\"\">[email protected]</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:[email protected]?subject=TEST")); 
       } catch (URISyntaxException | IOException ex) { 
        //It looks like there's a problem 
       } 
      } 
     }); 
    } 
} 
4

我知道我有點遲到了,但我犯了一個小方法,別人可能會覺得涼爽/有用。

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

它會給你一個JLabel,就像一個適當的鏈接。

在行動:

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

如果您想無提示只發送一個空。

希望有人認爲這有用! (如果你這樣做,一定要讓我知道,我很樂意聽到。)

4

使用JEditorPaneHyperlinkListener

2

只要把window.open(website url),它每次都有效。

1

以下代碼需要將JHyperLink添加到您的構建路徑中。

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

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

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

請注意,您可以填寫JComponent陣列更Swing組件。

結果:

1

您可以在一個

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

使用,或者如果你想使用Internet Explorer或Firefox與iexplorefirefox