Когда я запускаю свой простой Java-браузер, я пытаюсь посетить веб-страницу, такую как http://google.com, и он возвращает ошибку NullPointerException из моего кода catch catch, как бы исправить это?
Класс кадра:
public class Frame extends JFrame {
public EditorPane pane;
public URLBar urlbar;
public static void main(String[] args) throws Exception {
Frame frame = new Frame();
}
public Frame() throws Exception {
super("Java Browser v1.0");
JPanel mainPanel = new JPanel(new BorderLayout());
URLBar addressBar = new URLBar("Enter URL here!", pane);
EditorPane contentDisplay = new EditorPane(urlbar);
mainPanel.add(contentDisplay, BorderLayout.CENTER);
mainPanel.add(addressBar, BorderLayout.NORTH);
add(mainPanel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(700, 400);
add(new JScrollPane(mainPanel));
setVisible(true);
}
}
Класс URLBar:
public class URLBar extends JTextField {
public EditorPane pane;
public URLBar(String text, EditorPane pane) {
super(text);
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
loadContent(event.getActionCommand());
}
}
);
}
public void loadContent(String userInput) {
try
{
pane.setPage(userInput);
setText(userInput);
}
catch (Exception e)
{
System.out.println("A wild exception appeared! Type: " + e);
}
}
}
Класс EditorPane:
public class EditorPane extends JEditorPane {
public URLBar urlbar;
public EditorPane(URLBar urlbar) {
setEditable(false);
setVisible(true);
addHyperlinkListener(
new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent event) {
if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED) {
urlbar.loadContent(event.getURL().toString());
}
}
}
);
}
}
Похоже, вы забыли URLBar
элемент pane
в своем конструкторе URLBar
, а это значит, что при вызове loadContent
он имеет значение null.
Здесь исправление:
public URLBar(String text, EditorPane pane) {
super(text);
this.pane = pane; // add this
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
loadContent(event.getActionCommand());
}
}
);
}