lameraz
lameraz

Reputation: 11

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

Upvotes: 1

Views: 370

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Here in your actionPerformed method:

    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.

The key is to get a reference to the viewed LView object, and in this actionPerformed method, call this method on that object. 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.

Upvotes: 3

Related Questions