Search code examples
javamodel-view-controllercomboboxjcombobox

Trouble with Combobox and MVC pattern


I got a small Problem with a JComboBox and the MCV Pattern.

In my View package i got a class gui. This contains the combobox.

    package view;
    public class Gui {
    .........
    public JComboBox<OceanObject> oceanBoxDelete = new ComboBox<OceanObject> 
    ();
    this.down.add(this.oceanBoxDelete);

    this.oceanBoxDelete.setSize(40, 1);
    .......

This also contains a button. If the button gets hit it triggers a swith trough a button listener/action listener. This switch is supposed to trigger a procedure with removes an object from the list. If i put the action listener into the same java file it works but I'm not allowed to do so. If i put it into the button listener file i get an null pointer exeception when entering the combobox with the comment unknown source and .

My button listener looks like:

    package control;
    import view.Gui;

    public class ButtonListener implements ActionListener{

    private Gui gui;

    public ButtonListener() {
    this.ocean = ocean;
    }

   @Override
   public void actionPerformed(ActionEvent ae) {

    switch (ae.getActionCommand()) {
    ....
    case "Delete":
        System.out.println("deleteButton wurde gedrueckt.");

        OceanObject oObject = (OceanObject)   
        gui.oceanBoxDelete.getSelectedItem());
        go.removeOceanOjectFromOcean(oObject);
    .......

I can see that the right switch is triggered since the println is displayed right in the console.

So i think the problem is that the problem is, that the getSelectedItem cant see the combobox and i need to make it known to it, but how?


Solution

  • In the ButtonListener class you aren't initializing gui in the constructor. Unless you're passing it through some other method which isn't listed, it's null when you're accessing it in actionPerformed().

    You can pass gui and anything else the ButtonListener needs to the constructor:

    public ButtonListener(Gui gui, Ocean ocean, Go go) {
        this.gui = gui;
        this.ocean = ocean;
        this.go = go;
    }
    

    Then when you are creating the ButtonListener in the Gui class, you need to provide the actual values:

    this.deleteButton.addActionListener(new ButtonListener(
            this,
            this.oceanPanel.getOcean(),
            this.go
    ));
    

    I'm guessing oceanPanel.getOcean() provides the Ocean instance - if not, change it as needed.