我在这里做错了什么?我有一个显示我的列表的GUI和另一个我希望在单击按钮时添加到列表的类。单击按钮时,它会询问名称,但永远不会添加。
//class with GUI
public class LView extends MasterViewPanel {
private JList players, square;
private DefaultListModel playerModel;
private LobbyModel lm;
private Player pl;
public LView(RiskMasterView m) {
super(m);
setUpLists();
}
private void setUpLists() {// create list specify size, location.
playerModel = new DefaultListModel();
players = new JList(playerModel);
players.setSize(150, 250);
players.setLocation(535, 200);
this.add(players);
//add players
}
public void addPlayers() {
String name = JOptionPane.showInputDialog(playerModel, "Enter Name");
playerModel.addElement(name);
}
}
//class with with button to add to the list
public class TView extends MasterViewPanel {
RiskMasterView rmv;
public TView(RiskMasterView m) {
super(m);
rmv = m;
setUpGui();
}
private class LListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
LView pl = new LView(m);
pl.addPlayers();
rmv.switchViews(Views.LOB);
}
}
}
答案 0 :(得分:3)
此处在您的actionPerformed方法中:
public void actionPerformed(ActionEvent arg0) {
LView pl = new LView(m); // **** here ****
pl.addPlayers();
rmv.switchViews(Views.LOB);
}
您正在上面指出的位置创建一个新的LView对象,并在此LView对象上调用addPlayers,但它不当前正在显示的LView对象,所以应该不会感到惊讶显示的JList未更新。
关键是获取对已查看的LView对象的引用,并在此actionPerformed方法中,在该对象上调用此方法。你如何做到这将取决于你没有向我们展示的代码,但也许它可以通过RiskMasterView对象获得,但同样,我不知道你到目前为止所展示的内容。