java - 如何在 JLabel 中添加超链接?

标签 java swing hyperlink jlabel

在 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/

相关文章:

java - 如何从不同的类获取文本文件的输入

java - 在 JLabel 上设置大小会取代 java 中的其他组件

java - JSplitPane 上的绘图未显示

java - 使用 64 位指令从命令行调用 jMeter 会丢失类

java - EmbeddedKafkaBroker 设置属性抛出 NoClassDefFoundError : kafka/zk/EmbeddedZookeeper

java - 将文本框放在单独的行中

java - HTML 字段 json 编码为深层嵌套对象

javascript - React - 单击按钮转到视口(viewport)顶部

javascript - 如何使用 Casperjs 检查网页中损坏的链接?

php - 保护通过电子邮件发送的delete.php链接