我在为 JButton 添加 ActionListener 时遇到问题,请帮助解决这个问题。
错误:
Exception in thread "main" java.lang.NullPointerException
at searchDB.searchDB(searchDB.java:11)
at Ramses.main(Ramses.java:35)
主类:Ramses.java
import javax.swing.JFrame;
import ...........;
public class Ramses {
public static void main(String[] args) {
// TODO Auto-generated method stub
Gui GuiObject = new Gui();
GuiObject.Gui();
searchDB searchObject = new searchDB();
searchObject.searchDB(); //error here
}
}
声明 JButton 的类:Gui.java
import javax.swing.*;
import........;
public class Gui {
public static JButton btnUpdate;
public void Gui() {
JButton btnSearch = new JButton("Search");
btnSearch.setBounds(463, 112, 91, 23);
btnSearch.setVisible(true);
pnUpper.add(btnSearch);
}
}
实现JButton ActionListener的类:searchDB.java
import javax.swing.*;
public class searchDB{
public void searchDB(){
HandlerClass handler = new HandlerClass();
Gui.btnSearch.addActionListener(handler); //error in this line
}
private class HandlerClass implements ActionListener{
@Override
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
String cstmrSearch = (String) Gui.cbCustomer.getSelectedItem();
System.out.println("Selected Customer is :"+cstmrSearch);
}
}
}
任何想法这段代码有什么问题?