Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: NullPointerException on ActionListeners

  1. #1
    Junior Member
    Join Date
    Dec 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default 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 :

    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

    Okay, my full code...this is gonna be big:

    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.
    Last edited by cherryduck; December 7th, 2010 at 02:13 PM. Reason: Fixed it!


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default 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
    JButton backButton = new JButton("Back");

    to

    backButton = new JButton("Back");

    Edit: oops, noticed your edit. Problem solved?

  3. #3
    Junior Member
    Join Date
    Dec 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: NullPointerException on ActionListeners

    Yes I did exactly that, but thanks for taking the time to reply.

Similar Threads

  1. [SOLVED] Nullpointerexception
    By kbwalker87 in forum What's Wrong With My Code?
    Replies: 7
    Last Post: October 14th, 2010, 10:33 PM
  2. [SOLVED] NullPointerException
    By javapenguin in forum What's Wrong With My Code?
    Replies: 13
    Last Post: October 1st, 2010, 12:10 AM
  3. NullPointerException
    By bbr201 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: July 29th, 2010, 07:06 PM
  4. Funny NullPointerException
    By Marcus in forum What's Wrong With My Code?
    Replies: 4
    Last Post: December 6th, 2009, 10:14 AM
  5. NullPointerException in Java
    By jazz2k8 in forum Exceptions
    Replies: 9
    Last Post: June 1st, 2008, 05:59 PM