开发者

NullPointerException when accessing another class in ActionListener

I am trying to add an ActionListener to a JButton in the standard way: outside of the method I have private Actions listener;and inside of the method I have put

listener = new Actions(); // Create the action listener object 

    // Add action listeners to the necessary components
    isDatabaseDefault.addActionListener(listener);
    addEntry.addActionListener(listener);
    editEntry.addActionListener(listener);
    deleteEntry.addActionListener(listener);
    addDatabase.addActionListener(listener);
    editDatabase.addActionListener(listener);
    deleteDatabase.addActionListener(listener);

AND that is working fine, no errors are found - here is the ActionListener class:

package engines;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import graphicalUI.Tabs;

public class Actions implements ActionListener, SoftwareProperties{
    // Create objects to access methods
    private DatabaseManagement database;
    private Tabs tabs;

    public Actions(){
        this.database = new DatabaseManagement();
        this.tabs = new Tabs();
    }

    // Method that is called when a button is clicked
    public void actionPerformed(ActionEvent e) {
        // Check the source of the action
        if(e.getActionCommand().equals("Make a new database")){
            System.out.println("Null pointer exception");
            String location = database.makeNewDatabase();
            if(location==null){
                JOptionPane.showMessageDialog(null, "Error: Your new database was not successfully created. Please try again if you like.", applicationName, JOptionPane.WARNING_MESSAGE);
                return;
            }
                        tabs.updateDatabaseMCombo();
            tabs.setDatabaseManagementContent(location, true);
        }
    }

}

When I press the button though "Null Pointer Exception" prints out, and the database.makeNewDatabase(); runs, but as soon as it gets to either of the methods inside the tabs class, I receive the following error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at graphicalUI.Tabs.updateDatabaseMCombo(Tabs.java:148) at engines.Actions.actionPerformed(Actions.java:31) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$000(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)

But the weird thing is, when I run these methods from the same class they work perfectly! Here is the updateDatabaseMCombo() method:

public void updateDatabaseMCombo(){
        System.out.println("is this method running");
        int sIndex = selectDatabase.getSelectedIndex(); // Get the number value of the selected item
        String selectedItem = selectDatabase.getItemAt(sIndex); // Get the string of the selected item
        System.out.println(selectedItem);
        availableDBs4DM = db.getAvailableDatabases4DB(null); // Get a list of available databases to manage
        selectDatabase.removeAllItems(); // Remove all the current items in the combo
        // Loop through the array and manually add each item
        for(String item : availableDBs4DM)
            selectDatabase.addItem(item);
        // Select the item that was previously selected 
        int search = -1; // Initialise variable to hold the search results
        for(int s = 0; s < availableDBs4DM.length; s++){
            // If a match is found, update the search variable and stop searching
            if(availableDBs4DM[s].equals(selectedItem)){
                search = s;
                break;
            }
        }

        if(search != -1){
            // If the database that was previously selected is still in the JCombobox
            selectDatabase.setSelectedIndex(search);
        }else{
            // Select the default database
            db.setTranslationDefaultDB(selectDatabase)开发者_开发百科;
        }
    }

So can anyone work out why I am getting this error please?

BTW, selectDatabase has already been initialised as a JComboBox<String> object.


UPDATE


Okay, after some debugging, I found out that my NullPointerException was because I was only declaring the variable out side of the method, like so private JComboBox<String> selectDatabase; and I was actually initialising it in a different method, like so:

package test;
import java.awt.FlowLayout;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;

import test2.Runner;


public class DBCombo {
    private JComboBox<String> combo = new JComboBox<String>();

    public JPanel makePanel(){
        JPanel panel = new JPanel(new FlowLayout());

        String[] options = {"Why", "will", "this", "not", "work"};
        combo.setModel(new DefaultComboBoxModel<String>(options));

        panel.add(combo);

        Runner main = new Runner();

        JButton doRead = new JButton("Read");
        doRead.addActionListener(main);

        panel.add(doRead);

        return panel;
    }

    public void getComboData(){
        System.out.println(combo.getItemCount());
    }
}

package test2;


import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;

import test.DBCombo;


public class Runner implements ActionListener {
    public static void main(String[] args){
        JFrame frame = new JFrame("Test");

        DBCombo dbc = new DBCombo();

        frame.setContentPane(dbc.makePanel());
        frame.pack();
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e){
        new DBCombo().getComboData();
    }
}

Any idea's anyone?

I now think that it is because the action listener and the method are in different packages...


Okay, unfortunately it's not exactly what I had in mind or wanted to do, but I have at least got it working now!

It turns out, for some reason still unbeknown to me, that any other class apart from the Tabs class itself that called updateDatabaseMCombo() or setDatabaseManagementContent(String, boolean)generated null pointers! So, I've just bit the bullet and put the actionlistener inside of the Tabs class...

Oh well, it's not like my end users will know any different.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜