NetBeans. UI created using IDE.
My implementation In order of appearance:
1 global form variable:
private DefaultListModel model;
2 constructor:
ArrayList<String> cameras = repository.getCameraNames();
model= new DefaultListModel();
for (int i = 0; i < cameras.size(); i++) {
model.addElement(cameras.get(i));
}
thelist.setModel(model);
3 remove button:
private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {
int index = thelist.getSelectedIndex();
model.removeElementAt(index);
}
On the removeElementAt line, I get NullPointerException. If i change the index for a explicit number, it works but doesn’t with the index variable. But the selected index, doesn’t work!
Anyone can help?
Oh, and here is some stackttrace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at FrmPrincipal.thelistValueChanged(FrmPrincipal.java:217)
at FrmPrincipal.access$000(FrmPrincipal.java:22)
at FrmPrincipal$1.valueChanged(FrmPrincipal.java:77)
at javax.swing.JList.fireSelectionValueChanged(JList.java:1798)
at javax.swing.JList$ListSelectionHandler.valueChanged(JList.java:1812)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:184)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:164)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:211)
at javax.swing.DefaultListSelectionModel.removeIndexInterval(DefaultListSelectionModel.java:677)
at javax.swing.plaf.basic.BasicListUI$Handler.intervalRemoved(BasicListUI.java:2601)
at javax.swing.AbstractListModel.fireIntervalRemoved(AbstractListModel.java:179)
at javax.swing.DefaultListModel.removeElementAt(DefaultListModel.java:332)
UPDATE
I fixed by changing the following method:
private void thelistValueChanged(javax.swing.event.ListSelectionEvent evt) {
txtCameraName.setText(thelist.getSelectedValue().toString());
}
To
private void thelistValueChanged(javax.swing.event.ListSelectionEvent evt) {
txtCameraName.setText((String)thelist.getSelectedValue());
}
But I don’t know why!
Can someone explain why it didn’t accept the toString() and accepted the casting?
Your change “fixed” your problem because
getSelectedValue().toString()will throw a NPE if there is no selection, whereas(String)getSelectedValue()will evaluate tonullif there is no selection. But, if you ever put things in your list that aren’tStrings, then you’ll getClassCastExceptions when you try to cast the selected value to aString. So, this may have solved your current problem, but it’s not a solution really.I would just do this: