I’ve got a problem connected with my previous question: JList: sorting by Up/down buttons
My Up/Down buttons work properly now, but here’s the other thing:
I need to make Top/Bottom buttons also. They seem to be harder. I use actionPerformed to button “Top”:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int indexOfSelected = jList1.getSelectedIndex();
swapElements2(indexOfSelected, 0);
indexOfSelected = 0;
jList1.setSelectedIndex(indexOfSelected );
jList1.updateUI();
}
And swapElements2 method looks like that:
private void swapElements2(int pos1, int pos2) {
String tmp1 = (String) listModel.get(pos1);
String tmp2 = (String) listModel.get(pos2);
listModel = (DefaultListModel) jList1.getModel();
int sizeOfList = listModel.getSize();
listModel.set(pos2, listModel.get(sizeOfList-1));
for (int i=sizeOfList-2;i>0;i--){
listModel.set(i+1, listModel.get(i));
}
listModel.set(pos2, tmp1);
listModel.set(pos2+1, tmp2);
}
Of course, it works only if the last element of jList is selected. Has anyone an idea how to make an universal method which will move the element from selected position to 0 position? Method should also move all other elements forwards and the last element should stay at it’s place if it’s not selected.
I’d be grateful for any help.
Edit from comments, which also doesn’t work:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String temp = (String) listModel.remove(jList1.getSelectedIndex());
listModel.add(0, temp);
}
Error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
name podziwiaj.jpg
at java.io.File.<init>(File.java:222)
Which is:
public File(String pathname) {
if (pathname == null) {
throw new NullPointerException();
}
this.path = fs.normalize(pathname);
this.prefixLength = fs.prefixLength(this.path);
}
List stores path names of files (images) and displays is, when item is selected.
My own preference is to work with the list’s model to do this. Something like:
To see what methods are available to the list’s model, please check out the DefaultListModel API.
Edit: code works fine.
Edit 2: My sscce
If you’re still stuck after reviewing this, then consider reading about SSCCE, and posting your own here that we can modify and correct.
Edit 3
Per our discussions in chat,
Your problem is when you call the To Top JButton, you are deleting the selected item from the list, while the ListSelectionListener is still listening, and this will cause a NPE to be thrown. A possible solution is to remove the ListSelectionListener before removing or adding any items, and then re-adding the listener after performing these actions. This will probably be necessary when you update your list model as well. Please see my SSCCE below. Also see how it is much easier to read and understand SSCCE code than your big code.