我正在尝试向JPanel添加超链接。我想将它的文本设为蓝色(并加下划线),并且链接应该是可选的(复制它的某些部分)。所以我尝试使用JLabel:是的,它允许像这样写一些[糟糕]:
someLabel.setText("<html><font color=\"#0000ff\"><u>http://example.com</u></font></html>");
但不幸的是,JLabel不允许选择任何文字。我也试过使用JTextField,但相反,它不允许在它的字段中使用HTML / CSS。
那么,是否存在使用基本Swing组件创建超链接(具有适当指示)的任何方式,允许选择[并复制]其中的一部分,或者我应该尝试使用某些第三方组件?谢谢。
答案 0 :(得分:5)
您可以在不可编辑的JEditorPane
中显示HTML内容。它是可选择的,您可以通过HyperlinkListener
:
JEditorPane content = new JEditorPane();
content.setContentType("text/html");
content.setEditable(false);
content.setText("<html><a href=\"http://stackoverflow.com\">Link</a></html>"));
content.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
Desktop.getDesktop().browse(e.getURL().toURI());
} catch (Exception e1) {
Logger.getLogger(getClass()).error(
"Error opening link " + e.getURL(), e1);
}
}
}
});
答案 1 :(得分:1)
在这里如何创建一个带有超链接的JLabel,然后你可以将它添加到你的Jpanel:
public HyperLinkLabel()
{
JPanel p = new JPanel();
final String strURL = "http://www.yahoo.com";
final JLabel label = new JLabel("<html><a href=\" " + strURL + "\"> click </a></html>");
final JEditorPane htmlPane = new JEditorPane();
p.add(label);
getContentPane().add(BorderLayout.NORTH, p);
getContentPane().add(BorderLayout.CENTER, new JScrollPane(htmlPane));
setBounds(20,200, 500,500);
label.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
label.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent me) {
label.setCursor(Cursor.getDefaultCursor());
}
public void mouseClicked(MouseEvent me)
{
System.out.println("Clicked on Label...");
try {
htmlPane.setPage(new URL(strURL));
}
catch(Exception e) {
System.out.println(e);
}
}
});
答案 2 :(得分:1)
答案 3 :(得分:0)
您必须创建自定义Jlabel
[扩展Jlabel
]并为MouseListener
写一个JLabel
。
当用户单击自定义JLabel
时,您的鼠标侦听器必须执行将用户定向到链接的工作。您正在寻找的鼠标事件[基本上是您必须编写重定向代码的MouseListener
接口的方法]是mouseClicked
。