我有一个HashMap<Person, ArrayList<Account>>
,我想要一个包含来自HashMap的所有键(人)的表。问题是如果我尝试在视图中创建它,表是空的,但如果我在main中创建它(使用完全相同的代码)它可以工作并填充数据。我不知道为什么。
public class App
{
public static void main( String[] args )
{
View view = new View();
Bank b = new Bank();
Person p = new Person("Name","Prenume", "id");
Person p1 = new Person("Name2","Prenume2", "id2");
b.addPerson(p);
b.addPerson(p1);
view.personTbl = view.tablePers(b.mapper);
view.sp = new JScrollPane(view.personTbl);
view.personFrame.add(view.sp,BorderLayout.CENTER);
view.viewPers.setVisible(true);
}
}
如果我像这样创建它不起作用
public View() {
personFrame = new JFrame("Person");
personFrame.setLayout(new BorderLayout());
personFrame.setSize(400, 400);
persBtnsPan = new JPanel();
viewPers = new JFrame("View Pers");
viewPers.setLayout(new BorderLayout());
viewPers.setSize(400, 400);
viewPersPan = new JPanel();
addPerson = new JButton("add");
editPerson = new JButton("edit");
viewP = new JButton("view");
personTbl = tablePers(b.mapper);
sp = new JScrollPane(personTbl);
persBtnsPan.add(addPerson);
persBtnsPan.add(editPerson);
persBtnsPan.add(viewP);
personFrame.add(persBtnsPan, BorderLayout.NORTH);
personFrame.add(sp,BorderLayout.CENTER);
}
这是创建表的方法
public static <T> JTable tablePers(HashMap<Person, ArrayList<Account>> map) {
DefaultTableModel model = new DefaultTableModel(
new Object[] { "Nume", "Prenume", "CNP" }, 0);
for (HashMap.Entry<Person, ArrayList<Account>> entry : map.entrySet()) {
model.addRow(new Object[] { entry.getKey().getNume(), entry.getKey().getPrenume(), entry.getKey().getCnp() });
}
tab = new JTable(model);
return tab;
}
答案 0 :(得分:1)
您有参考问题,因为视图中的b.mapper
与主视图中的public class App {
Bank b = new Bank(); // the model
//... do things with b here
View view = new View(b); // pass the model in
// and then in View's constructor use the model
}
不同,但也不应该。但是,View处理这样的数据是没有意义的。您需要直接或间接将模型传递给View,然后让视图显示模型的状态。
如,
public static void main(String[] args) {
BankModel model = new BankModel();
model.addPerson(new BankPerson("LastName1", "FirstName1", "id1"));
model.addPerson(new BankPerson("LastName2", "FirstName2", "id2"));
BankView view = new BankView();
BankController controller = new BankController(model, view);
controller.displayGui();
}
此外,如果这是一个M-V-C程序,那么您的Controller将监听视图和模型的更改,并将通知相关实体更改,更新模型和视图。
如,
jQuery