tags:

views:

32

answers:

1

Hi Guys,

I am trying to move an item in a list upward but it is not working the way I want. The element that I select still remains after it has swapped position with the previous elements. I am using Jlist.

listTasks is a JLIst and listModel is ListModel

For instance if I have

1
2

as a list, after I select 2 and click the up button I get

2
1
2

This is the code snippet :

public void mouseClicked(MouseEvent e) {
        int id = 0;
        if(e.getSource() == this.lblUpArrow){
            id = this.listTasks.getSelectedIndex();
            if((id > 0 ) && (this.listModel.size() != 0)){
                Object value = this.listModel.getElementAt(id);
                Object previousValue = this.listModel.getElementAt(id - 1);
                this.listModel.insertElementAt(value.toString(), (id - 1));

                this.listTasks.remove(id);
                this.listModel.insertElementAt(previousValue.toString(), (id));

                this.listModel.remove(id + 1);

            }

        }
    }

Thanks for your help.

A: 

You just need to remove the element to move and re-insert it above the current position. No swap required.

gawi
You should also realize that your code is performing an insertion that will invalidate the value of id (that should really be called "index").
gawi
Thanks for your answer. It works
Kap