【问题标题】:How to have page change upon clicking <a> tag in JEditorPane?单击 JEditorPane 中的 <a> 标签后如何更改页面?
【发布时间】:2019-06-19 07:48:33
【问题描述】:

我在一个 html 页面上有一个“a”元素,带有一个用于不同网站的 href。目前,当我单击 JEditorPane 中显示的页面上的 a 元素时,JEditorpane 不会更改站点。它不会重定向到 href 的位置。如何在保持重定向页面显示在 JEditorPane 中的同时解决此问题?谢谢!

有问题的网站代码是:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a href="https://reddit.com"><img src="cat.jpeg" width="300" height="300" /></a>
</body>
</html>

JFrame和JEditorPane的代码是:

public class Gui 
{
    JFrame frame = new JFrame();
    JEditorPane htmlContent = new JEditorPane();

    public void loadScreen() throws MalformedURLException, IOException 
    {
        frame.setUndecorated(true);
        frame.setOpacity(1.0F);
        htmlContent.setEditable(false);
        htmlContent.setPage(new URL("RANDOM SITE"));
        frame.add(new JScrollPane(htmlContent));
        frame.setVisible(true);
    }
}

【问题讨论】:

    标签: java html swing jframe jeditorpane


    【解决方案1】:

    如果您希望JEditorPane 中显示的链接在鼠标单击时在窗格中加载新页面,您需要添加一个侦听器,如下所示:

    htmlContent.addHyperlinkListener(e->{
        if ( e.getEventType () == HyperlinkEvent.EventType.ACTIVATED ) {
            URL url = e.getURL ();
            // fetch the new page from the URL and load it into the JEditorPane
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      相关资源
      最近更新 更多