在ActionListener中访问另一个类时出现NullPointerException

时间:2023-02-04 17:29:00

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

我试图以标准方式将一个ActionListener添加到JButton:在方法之外我有私有的Actions侦听器;并且在我放入的方法内部

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:

并且工作正常,没有找到错误 - 这是ActionListener类:

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:

当我按下按钮时,“Null Pointer Exception”打印出来,而database.makeNewDatabase();运行,但只要它到达选项卡类中的任何一个方法,我收到以下错误:

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)

例外在线程 “AWT-EventQueue的-0” 在engines.Actions.actionPerformed(Actions.java:31)在javax.swing.AbstractButton.fireActionPerformed在graphicalUI.Tabs.updateDatabaseMCombo(Tabs.java:148)显示java.lang.NullPointerException(来源不明)在javax.swing.AbstractButton中$ Handler.actionPerformed(来源不明)在javax.swing.DefaultButtonModel.fireActionPerformed(来源不明)在javax.swing.DefaultButtonModel.setPressed(来源不明)在javax.swing.plaf.basic中。 java.awt.Lousener.mouseReleased(未知来源)位于java.awt.Compouse上的java.awtvent.Micicaster.mouseReleased(未知来源)java.awt.Component.processMouseEvent(未知来源)位于java.awt.Component的javax.swing.JComponent.processMouseEvent(未知来源)。 java.awt.Component上的java.awt.Container.ventEvent(未知来源)java.awt.ComptainerEventImpl(未知来源)处于java.awt.Component.dispatchEvent上的java.awt.ContainerEventImpl(未知来源)的processEvent(未知来源)来自java.awt.LightweightDispatcher.r的未知来源etargetMouseEvent(未知来源)在java.awt.LightweightDispatcher.processMouseEvent(未知来源)在java.awt.LightweightDispatcher.dispatchEvent(未知来源)在java.awt.Container.dispatchEventImpl(未知来源)在java.awt.Window.dispatchEventImpl(来自java.awt.EventQueue $ java的java.awt.EventQueue.access $ 000(未知来源)的java.awt.Component.dispatchEvent(未知来源)java.awt.EonentQueue $ 3.run(未知来源)来源不明)处java.security.AccessController.doPrivileged(本机方法)在java.security.ProtectionDomain $ 1.doIntersectionPrivilege(来源不明)java.awt.EventQueue中的$ 3.run(来源不明)在java.security.ProtectionDomain $ 1.doIntersectionPrivilege (java.sev.EventQueue上的java.awt.EventQueue $ 4.run(未知源)的未知源(未知源)java.security.ProtectionDomain $ 1上的java.security.AccessController.doPrivileged(Native Method)中的$ 4.run(未知源)。 java.awt.EventQueue.dispatchEve中的doIntersectionPrivilege(未知来源) NT(未知来源)在java.awt.EventDispatchThread.pumpOneEventForFilters(未知来源)在java.awt.EventDispatchThread.pumpEventsForFilter(未知来源)在java.awt.EventDispatchThread.pumpEventsForHierarchy(未知来源)在java.awt.EventDispatchThread.pumpEvents(来自java.awt.EventDispatchThread.run(未知来源)的java.awt.EventDispatchThread.pumpEvents(未知来源)的未知来源

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

但奇怪的是,当我从同一个类运行这些方法时,它们完美地工作!这是updateDatabaseMCombo()方法:

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.

BTW,selectDatabase已经初始化为JComboBox 对象。


UPDATE

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:

好的,经过一些调试后,我发现我的NullPointerException是因为我只是声明了方法的变量,就像私有的JComboBox selectDatabase;我实际上是用不同的方法初始化它,如下所示:

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...

我现在认为这是因为动作监听器和方法在不同的包中...

1 个解决方案

#1


2  

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...

事实证明,由于某些原因我仍然不知道,除了Tabs类本身之外的任何其他类调用updateDatabaseMCombo()或setDatabaseManagementContent(String,boolean)都会生成空指针!所以,我只是点击子弹并将actionlistener放在Tabs类中......

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

哦,这不像我的最终用户会知道任何不同。

#1


2  

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...

事实证明,由于某些原因我仍然不知道,除了Tabs类本身之外的任何其他类调用updateDatabaseMCombo()或setDatabaseManagementContent(String,boolean)都会生成空指针!所以,我只是点击子弹并将actionlistener放在Tabs类中......

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

哦,这不像我的最终用户会知道任何不同。