可能重复:
如何在 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
在这里,我必须将“两个”这个词作为可点击的链接来打开一个弹出窗口。
可能重复:
如何在 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
在这里,我必须将“两个”这个词作为可点击的链接来打开一个弹出窗口。
我个人会推荐使用 JEditorPane 而不是 JPanel;它对于显示段落更有用,并且可以显示 HTML,例如链接。然后,您可以简单地调用 addHyperlinkListener(Some 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
}
}
});
通常,当我们希望标签可点击时,我们只需将其设为按钮即可。我最近确实使用了标签而不是按钮,因为我发现更容易控制外观(图标周围没有边框),并且我希望标签看起来不同,具体取决于应用程序显示的某些数据。但无论如何,我可能已经用 JButton 完成了整个事情。
如果您只希望JLabel 的一部分可点击,那就更复杂了。单击鼠标时,您需要检查相对鼠标坐标,以查看它是否对应于您希望可单击的标签部分。
或者,您可能希望改为查看JEditorPane。这使您可以将 HTML 放入一个 Swing 应用程序中,然后您可能可以实现一些 HyperLinkListener。
但是如果你确实需要一个标签来触发一个动作,就像你最初要求的那样,你可以像这样向它添加一个鼠标监听器:
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.
}
});