简体   繁体   English

DefaultListModel不添加元素

[英]DefaultListModel not adding element

What am i doing wrong here? 我在这做错了什么? i have a GUI which displays my list and in another class i want to add to the list when button is clicked. 我有一个显示我的列表的GUI和另一个我希望在单击按钮时添加到列表的类。 When button is clicked it does ask for the name but it never gets added. 单击按钮时,它会询问名称,但永远不会添加。

//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);
        }
    }
}

Here in your actionPerformed method: 在你的actionPerformed方法中:

    public void actionPerformed(ActionEvent arg0) {
        LView pl = new LView(m); // **** here ****
        pl.addPlayers();
        rmv.switchViews(Views.LOB);
    }

You're creating a new LView object in the spot indicated above and calling addPlayers on this LView object, but it's not the LView object that is currently being displayed, so it should be no surprise that the displayed JList is not being updated. 您正在上面指定的位置创建一个新的LView对象,并在此LView对象上调用addPlayers,但是当前正在显示的不是 LView对象,因此显示的JList没有被更新也就不足为奇了。

The key is to get a reference to the viewed LView object, and in this actionPerformed method, call this method on that object. 关键是获取对查看的LView对象的引用,并在此actionPerformed方法中,在对象上调用此方法。 How you do this will depend on code that you've not shown us, but perhaps it can be obtained via the RiskMasterView object, but again, I don't know given what you've shown so far. 您如何执行此操作将取决于您尚未显示给我们的代码,但是也许可以通过RiskMasterView对象获得它,但是同样,鉴于您到目前为止所显示的内容,我仍然不知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM