有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在ActionListener中访问另一个类时发生java NullPointerException

我试图以标准的方式将ActionListener添加到JButton中:在我使用的方法private Actions listener;之外,在我使用的方法内部

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);

这很好,没有发现错误——这里是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);
        }
    }

}

当我按下按钮时,虽然会打印出“Null Pointer Exception”,并且database.makeNewDatabase();会运行,但一旦它到达tabs类中的任何一个方法,我就会收到以下错误:

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)

但奇怪的是,当我在同一个类中运行这些方法时,它们工作得非常好!以下是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);
        }
    }

有人能找出我为什么会犯这个错误吗

顺便说一句,selectDatabase已经被初始化为JComboBox<String>对象


更新


好的,在一些调试之后,我发现我的NullPointerException是因为我只是在方法的外面声明变量,比如private JComboBox<String> 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();
    }
}

有人知道吗

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


共 (1) 个答案

  1. # 1 楼答案

    好吧,不幸的是,这不完全是我的想法或想做的,但至少我现在已经开始工作了

    事实证明,出于某种我仍然不知道的原因,除了调用updateDatabaseMCombo()setDatabaseManagementContent(String, boolean)Tabs类本身之外,任何其他类都会生成空指针!所以,我刚刚咬紧牙关,把actionlistener放在Tabs类中

    我的最终用户不会知道有什么不同