gpt4 book ai didi

java - 如何修复 NullPointerException 错误?

转载 作者:太空宇宙 更新时间:2023-11-04 14:00:39 24 4
gpt4 key购买 nike

当我运行简单的 Java 浏览器时,我尝试访问诸如 http://google.com 之类的网页。它从我的 try catch 代码中返回 NullPointerException 错误,我该如何解决这个问题?

框架类:

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 成员,这意味着当您调用 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());
}
}
);
}

关于java - 如何修复 NullPointerException 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29333052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com