2012-07-24 52 views
0

可能重複:
How to add hyperlink in JLabel使用的JLabel作爲鏈接打開彈出

我使用「的JLabel」,顯示一個段落,我需要的那款爲紐帶的某些部分這將打開一個新的彈出窗口,請告訴我如何做到這一點,例如

this is ABC application and here is the introduction of the app: 
    this is line one 
    this is line two 
    this is line three 

在這裏,我必須讓單詞「two」作爲可點擊鏈接來打開彈出窗口。

回答

3

我個人會建議使用JEditorPane而不是JPanel;它顯示段落更有用,並且可以顯示HTML,例如鏈接。然後你可以簡單地調用addHyperlinkListener(一些hyperlinklistener)來添加一個監聽器,這個監聽器會在有人點擊鏈接時被調用。你可以彈出一些東西,或者打開任何在真正的瀏覽器中點擊的東西,它取決於你。

下面是一些示例代碼(沒有測試它,但應該工作):

JEditorPane ep = new JEditorPane("text/html", "Some HTML code will go here. You can have <a href=\"do1\">links</a> in it. Or other <a href=\"do2\">links</a>."); 
ep.addHyperlinkListener(new HyperlinkListener() { 
     public void hyperlinkUpdate(HyperlinkEvent arg0) { 
      String data = arg0.getDescription(); 
      if(data.equals("do1")) { 
       //do something here 
      } 
      if(data.equals("do2")) { 
       //do something else here 
      } 
     } 
    }); 
1

通常,當我們希望有一個標籤,可以點擊,我們只是讓一個按鈕。我最近使用Label來代替按鈕,因爲我發現它更容易控制外觀(圖標周圍沒有邊框),並且我希望標籤看起來不同,這取決於應用程序顯示的一些數據。但我可能可以用JButton完成整個事情。

如果你只想要你的JLabel的部分是可點擊的,那會變得更加複雜。您需要檢查鼠標單擊時的相對鼠標座標,以查看它是否與您想要點擊的標籤部分相對應。

或者,您可能想要看看JEditorPane。這可以讓你把HTML放到一個swing應用中,然後你可以實現一些HyperLinkListener。

但是,如果你需要一個標籤火的動作,如您最初的要求,你可以一個的MouseListener添加到它是這樣的:

noteLabel = new JLabel("click me"); 
noteLabel.addMouseListener(new MouseAdapter() { 
    public void mousePressed(MouseEvent e) { 
     System.out.println("Do something"); 
    } 

    public void mouseEntered(MouseEvent e) { 
     //You can change the appearance here to show a hover state 
    } 

    public void mouseExited(MouseEvent e) { 
     //Then change the appearance back to normal. 
    } 
});