我只想补充一点,加载的初始文件是一个包含所有类名称的 javadoc,当我点击带有它的名称的超链接时,我希望它显示每个类的相应页面,当我打印时在控制台中,我没有看到收集相应 url 的任何问题,但是每次我尝试将它添加到 JEditorPane 时都会收到 NullPointerException。
这是我的程序:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class Help implements HyperlinkListener
{
JEditorPane htmlPane;
String url = "file:///F:/java%2012/Isp/help%20file%20try/doc%202/allclasses-frame.html";
public void hyperlinkUpdate(HyperlinkEvent event) {
if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
htmlPane.setPage(event.getURL());
//url.setText(event.getURL().toExternalForm());
//System.out.println(event.getURL().toString());
}
catch(IOException ioe) {
// System.out.print("err");
// Some warning to user
}
}
}
public void frame()
{
JFrame frame = new JFrame("asdd");
JLabel l = new JLabel("asdsada");
try
{
JEditorPane htmlPane = new JEditorPane(url);
htmlPane.addHyperlinkListener(this);
htmlPane.setEditable(false);
frame.add(new JScrollPane(htmlPane));
}
catch(IOException ioe) {
System.err.println("Error displaying " + url);
}
frame.setSize(1200,800);
frame.setVisible(true);
}
public static void main(String[] args)
{
Help h =new Help();
h.frame();
}
}
最佳答案
但是你从哪里得到这个NullPointerException
?
我运行了您的示例代码,并在以下情况下得到了 NullPointerException
:
htmlPane.setPage(event.getURL());
所以 htmlPage
字段是 null
。
添加行时:
this.htmlPane = htmlPane;
在:
public void frame() {
JFrame frame = new JFrame("asdd");
JLabel l = new JLabel("asdsada");
try {
JEditorPane htmlPane = new JEditorPane(url);
this.htmlPane = htmlPane;
我现在可以点击任何链接(在我的例子中是“http://www.google.com/”)
关于java - 每次我单击 JEditorPane 中的超链接时,hyperlinkUpdate() 都会给我 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10889875/