如何在JLabel中添加超链接?
在 JLabel 中添加超链接的最佳方法是什么?我可以使用html标签获取视图,但是当用户单击浏览器时如何打开它?
在 JLabel 中添加超链接的最佳方法是什么?我可以使用html标签获取视图,但是当用户单击浏览器时如何打开它?
您可以使用 来执行此操作,但另一种方法是设置 JButton 的样式
。这样,您就不必担心可访问性,只需使用操作管理器
触发事件即可。JLabel
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 */ }
}
我想提供另一种解决方案。它类似于已经提出的那些,因为它在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);
}
});
}
}