我没有得到MVC

时间:2015-12-18 09:45:07

标签: java swing windowbuilder



.catch()




嗨,我很难掌握MVC设置。我正在研究一个学校项目,我正在使用swing / windowbuilder来创建UI。现在的问题是当我按下jbutton" Spara"时,我得到一个nullpointerexception。这被认为是创建类Customerand的新对象,从文本框中获取所有信息,然后将对象添加到我在名为CustomerReg的类中的arraylist中。和客户名单。我还包括控制器类。

控制器

package com.schinbehn.model;

import java.util.ArrayList;

public class CustomerReg {

	private ArrayList<Customer> customerList;

	
	
	
	public ArrayList<Customer> getCustomers() {
		return customerList;
	}

	public void setCustomers(ArrayList<Customer> newCustomers) {
		customerList = newCustomers;
	}

	public void addCustomer(Customer c) {
		customerList.add(c);
	}

	public Customer findCustomer(String orgNummber) {
		for (Customer tmp : customerList) {
			if (orgNummber.equals(tmp.getOrgNumber())) {
				return tmp;
			}
		}
		return null;
	}

}

查看

package com.schinbehn.controller;

import com.schinbehn.model.Customer;
import com.schinbehn.model.CustomerReg;

public class Controller {

  private CustomerReg customers;
  private Customer customer;


  public Controller() {
    customers = new CustomerReg();

  }

  public Customer findCustomer(String orgNumber) {
    return customers.findCustomer(orgNumber);

  }

  public void addCustomer(Customer k) {
    customers.addCustomer(k);
  }



}

1 个答案:

答案 0 :(得分:1)

NPE的原因是您的customerReg永远不会在ApplicationView类中创建:

ApplicationView

的成员部分写下此内容
private CustomerReg customerReg = new CustomerReg();

或者更好。让控制器完成这项工作。但是也必须创建controller(在代码中不是这样):

private Controller controller = new Controller();

  @Override
  public void actionPerformed(ActionEvent e) {
    Customer c = new Customer();
    c.setOrgNumber(textFieldOrgNr.getText());
    c.setCompanyName(textFieldComanyName.getText());
    c.setBillingAdress(textFieldBillingAdress.getText());
    c.setCompanyContact(textFieldCompanyContact.getText());
    c.setEmail(textFieldEmail.getText());
    c.setAgreement(textFieldAgreement.getText());
    c.setPhoneNumber(textFieldPhoneNumber.getText());

    controller.addCustomer(c);

  }
});