2012-07-24 49 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. 
    } 
});