我仍然是使用 MVC 的新手,并且使用 ActionListener 给我一个运行程序的问题,在这种情况下,NullPointerException 作为输出出现。
目的是有一个后退按钮,可将用户从第二菜单返回到主菜单。
当我在控制器上注释掉这一行时,错误就消失了。 this.theView.addComBackButtonListener(new CompanyBackBtnListener());
如果我错了,请纠正我,但我认为它似乎无法找到 CompanyBackBtnListener,即使它在那里。
- 已经检查错别字了。
我试图缩小编码范围。如果我错过任何细节如果您有任何解决方案,请告诉我如何,因为我仍在学习 Java。谢谢你。
风景
public class HRMSViewGUI extends JFrame {
//Declarations here
private JButton exitCusBtn;
// Main Menu
public HRMSViewGUI()
{
this.setTitle("Human Resource Management System");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setSize(600,225);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.add(HRMSMenu);
// Main Menu GUI/Buttons place here.
// This contains the Main Menu buttons and GUI only.
// Second Menu
public void comMenu(){
comFrame = new JFrame();
comFrame.setTitle("Company Menu - HRMS SYSTEM");
comFrame.setResizable(false);
comFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
comFrame.setSize(600,225);
comFrame.setLocationRelativeTo(null);
comFrame.setVisible(true);
// Swings Codings... Buttons.
// This is the Back/Return button.
GridBagConstraints cusConc = new GridBagConstraints();
exitCusBtn = new JButton("Exit to Menu");
exitCusBtn.setToolTipText("Go back to the Main Menu.");
cusConc.gridx = 3;
cusConc.gridy = 8;
cusConc.fill = GridBagConstraints.HORIZONTAL;
cusConc.insets = new Insets(5,0,0,0);
cusContainer.add(exitCusBtn,cusConc);
}
void addComBackButtonListener(ActionListener listenerforComBackButton){
exitComBtn.addActionListener(listenerforComBackButton);
}
}
控制器
public class HRMSControlGUI {
private HRMSViewGUI theView;
private HRMSModel theModel;
public HRMSControlGUI(HRMSViewGUI theView, HRMSModel theModel){
this.theView = theView;
this.theModel = theModel;
//set Listener for the Controller to detect the ActionListener of the View.
this.theView.addComBackButtonListener(new CompanyBackBtnListener());
}
private class CompanyBackBtnListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// Enable Main Menu
theView.setEnabled(true);
}
主要的
public class HRMSapp {
public static void main(String[] args) {
HRMSViewGUI theView = new HRMSViewGUI();
HRMSModel theModel = new HRMSModel();
HRMSControlGUI theController = new HRMSControlGUI(theView, theModel);
theView.setVisible(true);
}