Doszi89
Doszi89

Reputation: 357

JList: sorting by Up/down buttons

Question: Is there an easy way to sort jList using Up/Down Buttons on jFrame? My JList stores path's of image files and displays string with name of the file. I would like to move down/up the element by clicking down/up Button.

Here's what I did - the effect is moving the selection (blue field), not the element. Button2 is button "up".

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    int indexOfSelected = jList1.getSelectedIndex();
    File selectedFile = (File) jList1.getSelectedValue();
    indexOfSelected = indexOfSelected - 1;
    jList1.setSelectedIndex(indexOfSelected );
    jList1.updateUI();

}

This is how the JList is created:

public void openButtonActionPerformed() {

        fc.setMultiSelectionEnabled(true);
        int returnVal = fc.showDialog(null, "Open");

         if (returnVal == JFileChooser.APPROVE_OPTION) { 
               file = fc.getSelectedFiles();
               len = file.length;
               System.out.println(len);   
         }    
         for (i=0; i<len; i++){ 
            listModel.add(i, file[i]);
         }
         jList1.setModel(listModel);
         jList1.updateUI();
}

Thank you for your help and patience - in advance. I'm a begginer:)

Upvotes: 1

Views: 3978

Answers (1)

Mikita Belahlazau
Mikita Belahlazau

Reputation: 15419

If you use list model, that supports set operation you can do following:

private void swapElements(int pos1, int pos2) {
    File tmp = (File) listModel.get(pos1);
    listModel.set(pos1, listModel.get(pos2));
    listModel.set(pos2, tmp);
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    int indexOfSelected = jList1.getSelectedIndex();
    swapElements(indexOfSelected, indesOfSelected - 1);
    indexOfSelected = indexOfSelected - 1;
    jList1.setSelectedIndex(indexOfSelected );
    jList1.updateUI();
}

Upvotes: 6

Related Questions