NullPointerException on ActionListeners
Hey guys, new to the forum, hope you're all well and looking forward to Christmas! Okay, so I'm trying to write a simple web browser, only every time I press a button or hit enter in the url field etc, anything which uses an ActionListener, nothing happens and I get stuff such as this in my debug output window :
Code :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at WebBrowser.backButtonActionPerformed(WebBrowser.java:113)
at WebBrowser.access$000(WebBrowser.java:9)
at WebBrowser$1.actionPerformed(WebBrowser.java:39)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6263)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3255)
at java.awt.Component.processEvent(Component.java:6028)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
My menus work just fine which is odd as they use ActionListeners :confused:
Okay, my full code...this is gonna be big:
Code :
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.IOException;
public class WebBrowser extends JFrame implements HyperlinkListener{
private JButton backButton, forwardButton;
private JTextField urlField;
private JEditorPane htmlPane;
private ArrayList pageList = new ArrayList();
private String defaultTitle = ("G52GUI Web Browser");
public WebBrowser(String initURL) {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("HTML Viewer Example");
setSize(800, 600);
JPanel navBarPanel = new JPanel();
JButton backButton = new JButton("Back");
JButton forwardButton = new JButton("Forward");
JTextField urlField = new JTextField(35);
JButton goButton = new JButton("Go");
JEditorPane htmlPane = new JEditorPane();
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem exitMenuItem = new JMenuItem("Exit");
JMenu bookmarksMenu = new JMenu("Bookmarks");
JMenuItem bookmarkMenuItem = new JMenuItem("Bookmark This Page");
navBarPanel.setBorder(BorderFactory.createEtchedBorder());
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
backButtonActionPerformed();
}
});
navBarPanel.add(backButton);
forwardButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
forwardButtonActionPerformed();
}
});
navBarPanel.add(forwardButton);
urlField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
urlFieldActionPerformed();
}
});
navBarPanel.add(urlField);
htmlPane.setContentType("text/html");
htmlPane.setEditable(false);
htmlPane.addHyperlinkListener(this);
goButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
goButtonActionPerformed();
}
});
navBarPanel.add(goButton);
exitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK));
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
exitMenuItemActionPerformed();
}
});
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
bookmarkMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_MASK));
bookmarksMenu.add(bookmarkMenuItem);
menuBar.add(bookmarksMenu);
setJMenuBar(menuBar);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(navBarPanel, BorderLayout.NORTH);
getContentPane().add(new JScrollPane(htmlPane),
BorderLayout.CENTER);
verifyAndLoad(initURL);
}
private void exitMenuItemActionPerformed() {
System.exit(0);
}
private void urlFieldActionPerformed() {
verifyAndLoad(urlField.getText());
}
private void goButtonActionPerformed() {
verifyAndLoad(urlField.getText());
}
private void backButtonActionPerformed() {
URL currentURL = htmlPane.getPage();
int pageIndex = pageList.indexOf(currentURL.toString());
try {
loadURL(new URL((String) pageList.get(pageIndex - 1)), false);
} catch (Exception e) {}
}
private void forwardButtonActionPerformed() {
URL currentURL = htmlPane.getPage();
int pageIndex = pageList.indexOf(currentURL.toString());
try {
loadURL(new URL((String) pageList.get(pageIndex + 1)), false);
} catch (Exception e) {}
}
public void hyperlinkUpdate(HyperlinkEvent evt) {
if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
{
try {
htmlPane.setPage(evt.getURL());
urlField.setText(evt.getURL().toExternalForm());
} catch(IOException ioe) {
errorMessage("Can't follow link to "
+ evt.getURL().toString());
}
}
}
private void verifyAndLoad(String url) {
URL verifiedURL = verifyUrl(url);
if(verifiedURL != null)
{
loadURL(verifiedURL, true);
} else {
errorMessage("Invalid URL");
}
}
private URL verifyUrl(String url) {
if (!url.toLowerCase().startsWith("http://www."))
{
url = "http://www."+url;
urlField.setText(url);
}
URL verifiedUrl = null;
try {
verifiedUrl = new URL(url);
} catch (MalformedURLException ex) {
return null;
}
return verifiedUrl;
}
private void loadURL(URL pageAddress, boolean addToList) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
setTitle("Loading...");
try {
URL currentURL = htmlPane.getPage();
htmlPane.setPage(pageAddress);
if (addToList) {
int listSize = pageList.size();
if (listSize > 0) {
int pageIndex = pageList.indexOf(currentURL.toString());
if (pageIndex < listSize - 1) {
for (int i = listSize - 1; i > pageIndex; i--) {
pageList.remove(i);
}
}
}
}
pageList.add(pageAddress.toString());
urlField.setText(pageAddress.toString());
} catch (Exception ex) {
errorMessage("Cannot load " + pageAddress.toString());
}
setCursor(Cursor.getDefaultCursor());
setTitle(defaultTitle);
}
private void errorMessage(String error) {
JOptionPane.showMessageDialog(this, error, "Error",
JOptionPane.ERROR_MESSAGE);
}
public static void main(String[] args) {
WebBrowser frame = new WebBrowser("http://www.google.co.uk");
frame.setVisible(true);
}
}
If you help I will give you a cookie! Only, not a real one cos I don't know where you live. But the thought is there!
EDIT:
NEVERMIND! I was stupid, I made my buttons and urlField, and then created local versions in my constructor. My other methods were using the global variables which of course hadn't been initialised.
Re: NullPointerException on ActionListeners
All the instance variables in the class will be null once the constructor exits. This is because you create local variables each with identical naming. This does not instantiate the actual instance variables, and these local variables loose scope after the constructor exits. As an example, change
Code :
JButton backButton = new JButton("Back");
to
Code :
backButton = new JButton("Back");
Edit: oops, noticed your edit. Problem solved?
Re: NullPointerException on ActionListeners
Yes I did exactly that, but thanks for taking the time to reply.