本文介绍了如何在 JLabel 中添加超链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 JLabel 中添加超链接的最佳方法是什么?我可以使用html标签获取视图,但是当用户点击它时如何打开浏览器?
What is the best way to add a hyperlink in a JLabel? I can get the view using html tags, but how to open the browser when the user clicks on it?
推荐答案您可以使用 JLabel 来做到这一点,但另一种方法是设置 JButton.这样,您就不必担心可访问性,只需使用 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("java.sun"); 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 中添加超链接?
发布评论