本文介绍了如何在JLabel中添加超链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在jLabel中添加超链接的最佳方法是哪种?我可以使用html标签获取视图,但是当用户点击它时如何打开浏览器?
Which is the best way to add a hyperlink in jLabel? I can get the view using html tags, but how to open the browser when the user clicks on it?
推荐答案
你可以做这使用 JLabel
,但另一种方法是设置。这样,您就不必担心,并且可以使用 ActionListener
。
You can do this using a JLabel
, but an alternative would be to style a JButton
. That way, you don't have to worry about accessibility and can just fire events using an ActionListener
.
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中添加超链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!