0
votes

Troubles getting JList getSelectedIndices and getComponents. Code shown is wrapped into an actionPerformed -> ActionListener of a button.

This is my piece of code:

public class PanelLeft extends JPanel {

    private DefaultListModel<String> dlm;
    private JList<String> list;
    
    public PanelLeft() {
        
        dlm = new DefaultListModel<String>();
        dlm.addElement("FOL");
        dlm.addElement("SSII");
        dlm.addElement("EEDD");
        dlm.addElement("Marcas");
        dlm.addElement("BBDD");
        dlm.addElement("Programación");
        
        list = new JList<String>(dlm);
        list.setFixedCellWidth(200);
        
        
        JScrollPane jsp = new JScrollPane(list);
        jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        
        add(jsp);
    }

    public JList<String> getList() {
        return list;
    }
}

For the ActionListener

class ControlToRight implements ActionListener {

    private PanelLeft pl;
    private PanelRight pr;
    
    public ControlToRight(PanelLeft panL,PanelRight panR) {
        pl = panL;
        pr = panR;
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        if(pl.getList().getSelectedValuesList() != null) {
            for(int i : pl.getList().getSelectedIndices()) {
                pr.getList().add(pl.getList().getComponent(i));
            }
        }
    }
}

It should add components from the left panel list (pl) to the right panel list(pr).

The actual result is nothing at all. It does nothing, no ArrayIndexOutOfBounds, nothing. It doesn't even jump into the for loop.

1
You are using JList wrong. Please read the documentation and the tutorial. - Sascha
Code updated, as I cant see nothing wrong with usage of the JList, neither my teacher. Sorry me, newbie here, now understanding the importance of well documented posts. - Vidal M.
A list contains data, not components. To move data from one list to another, you remove it from the model of the first one and add it to the model of the second one. - JB Nizet

1 Answers

0
votes

The reason you are not seeing anything is because you have not added the ControlToRight(ActionListener) to the list of listeners on any list.

Change:

public ControlToRight(PanelLeft panL,PanelRight panR) {
    pl = panL;
    pr = panR;
    pl.getList().addActionListener(this);
    pr.getList().addActionListener(this);
}