hyperlinkUpdate() gives me NullPointerException ev

2019-07-31 07:11发布

问题:

I just want to add that the initial file loaded is a javadoc that has the names of all the classes, I want it to display the corresponding page for each class when I click on the hyperlink with it's name, when i did prints in the console I didn't see any problems with gathering the corresponding url however I get a NullPointerException every time I try to add it to the JEditorPane.

Here's my program:

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();
   }
 }

回答1:

But where are you getting this NullPointerException?

I run your example code, and got NullPointerException on:

htmlPane.setPage(event.getURL());

so htmlPage field was null.

when added line:

this.htmlPane = htmlPane;

in:

public void frame() {
    JFrame frame = new JFrame("asdd");
    JLabel l = new JLabel("asdsada");
    try {
        JEditorPane htmlPane = new JEditorPane(url);
        this.htmlPane = htmlPane;

I can now click on any link (in my case in "http://www.google.com/")