Question

I'm going mad with this method which results in a runtime NullPointer exception when I remove a row in my database:

private void menuListValueChanged(javax.swing.event.ListSelectionEvent evt) {                                      
    int index = menuList.getSelectedIndex();
    int size = model.getSize();
    if (index >= 0) { 
        bDeleteMenu.setEnabled(true);
    } else { 
        bDeleteMenu.setEnabled(false);
        }
    Menu selectedMenu = (Menu)menuList.getSelectedValue();
    menuName.setText(selectedMenu.getMenuName());
}

The error is in this line: menuName.setText(selectedMenu.getMenuName());

and occurs only when I remove an item. This is the error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException. I guess this happens because when I remove the item in the Jlist the selection doesn't change automatically to the next one, or something like that.

And this is the method which I use to remove an item:

private void bDeleteMenuActionPerformed(java.awt.event.ActionEvent evt) {                                            
    Menu selectedMenu = (Menu)menuList.getSelectedValue();
    selectedMenu.getMenuName();
    int index = menuList.getSelectedIndex();
    DBConnection.deleteMenu(selectedMenu);
    int size = model.getSize();
    if (size == 0) { 
        bDeleteMenu.setEnabled(false);
    } else { 
        if (index == model.getSize()) {
            index--;
        }
        menuList.setSelectedIndex(index);
        menuList.ensureIndexIsVisible(index);
    }
    model.removeElement(selectedMenu);
    menuName.setText("");
}

Thank you!

Was it helpful?

Solution

Retrieving the name of the selected menu only makes sense in case where something is selected.

Replce

if (index >= 0) { 
    bDeleteMenu.setEnabled(true);
} else { 
    bDeleteMenu.setEnabled(false);
}
Menu selectedMenu = (Menu)menuList.getSelectedValue();
menuName.setText(selectedMenu.getMenuName());

with

if (index >= 0) { 
    bDeleteMenu.setEnabled(true);
    Menu selectedMenu = (Menu)menuList.getSelectedValue();
    menuName.setText(selectedMenu.getMenuName());
} else {
    bDeleteMenu.setEnabled(false);
}

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top