在 JLabel 中添加超链接的最佳方法是什么?我可以使用html标签获取 View ,但是当用户点击它时如何打开浏览器?
最佳答案
您可以使用 JLabel
来执行此操作,但另一种方法是设置 JButton
的样式.这样,您就不必担心 accessibility并且可以使用 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 */ }
}
关于java - 如何在 JLabel 中添加超链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/527719/