访问 ActionListener 中的另一个类时出现 NullPointerException
我正在尝试以标准方式将 ActionListener 添加到 JButton:在方法之外,我有 private 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);
并且工作正常,没有发现错误- 这是 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);
}
}
}
当我按下按钮时,虽然打印出“空指针异常”,并且 database.makeNewDatabase();
运行,但一旦它到达其中的任一方法选项卡类,我收到以下错误:
线程“AWT-EventQueue-0”中出现异常 java.lang.NullPointerException 在 GraphicUI.Tabs.updateDatabaseMCombo(Tabs.java:148) 处 Engines.Actions.actionPerformed(Actions.java:31) at javax.swing.AbstractButton.fireActionPerformed(来源未知)位于 javax.swing.AbstractButton$Handler.actionPerformed(来源未知)位于 javax.swing.DefaultButtonModel.fireActionPerformed(来源未知)位于 javax.swing.DefaultButtonModel.setPressed(来源未知)位于 javax.swing.plaf.basic.BasicButtonListener.mouseReleased(未知 来源)位于 java.awt.AWTEventMulticaster.mouseReleased(来源未知) 在 java.awt.Component.processMouseEvent(来源未知)处 javax.swing.JComponent.processMouseEvent(来源未知)位于 java.awt.Component.processEvent(来源未知)位于 java.awt.Container.processEvent(来源未知)位于 java.awt.Component.dispatchEventImpl(来源未知)位于 java.awt.Container.dispatchEventImpl(来源未知)位于 java.awt.Component.dispatchEvent(来源未知)位于 java.awt.LightweightDispatcher.retargetMouseEvent(来源未知)位于 java.awt.LightweightDispatcher.processMouseEvent(来源未知)位于 java.awt.LightweightDispatcher.dispatchEvent(来源未知)位于 java.awt.Container.dispatchEventImpl(来源未知)位于 java.awt.Window.dispatchEventImpl(来源未知)位于 java.awt.Component.dispatchEvent(来源未知)位于 java.awt.EventQueue.dispatchEventImpl(来源未知)位于 java.awt.EventQueue.access$000(来源不明)位于 java.awt.EventQueue$3.run(来源未知)位于 java.awt.EventQueue$3.run(来源未知)位于 java.security.AccessController.doPrivileged(本机方法)位于 java.security.ProtectionDomain$1.doIntersectionPrivilege(未知 来源)于 java.security.ProtectionDomain$1.doIntersectionPrivilege(未知 来源)位于 java.awt.EventQueue$4.run(来源未知) java.awt.EventQueue$4.run(来源未知)位于 java.security.AccessController.doPrivileged(本机方法)位于 java.security.ProtectionDomain$1.doIntersectionPrivilege(未知 来源)位于 java.awt.EventQueue.dispatchEvent(来源未知) java.awt.EventDispatchThread.pumpOneEventForFilters(来源未知) 在 java.awt.EventDispatchThread.pumpEventsForFilter(来源未知) 在 java.awt.EventDispatchThread.pumpEventsForHierarchy(未知 来源)位于 java.awt.EventDispatchThread.pumpEvents(来源未知) 在 java.awt.EventDispatchThread.pumpEvents(来源未知) java.awt.EventDispatchThread.run(来源未知)
但奇怪的是,当我从同一个类运行这些方法时,它们工作得很好!这是 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
对象。
更新
好吧,经过一些调试,我发现我的 NullPointerException 是因为我只是在方法之外声明了变量,就像这样 private JComboBox
我实际上是用不同的方法初始化它,就像这样:
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();
}
}
有人有什么想法吗?
我现在认为这是因为动作侦听器和方法位于不同的包中......
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,不幸的是,这并不完全是我想要做的,但我至少现在已经开始工作了!
事实证明,出于某种我仍然不知道的原因,除了
Tabs
类本身之外,任何其他类调用updateDatabaseMCombo()
或setDatabaseManagementContent(String, boolean )
生成了空指针!所以,我硬着头皮将 actionlistener 放在Tabs
类中...哦,好吧,我的最终用户不会知道有什么不同。
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 calledupdateDatabaseMCombo()
orsetDatabaseManagementContent(String, boolean)
generated null pointers! So, I've just bit the bullet and put the actionlistener inside of theTabs
class...Oh well, it's not like my end users will know any different.