Yki_Summer
Yki_Summer

Reputation: 27

Java - JList , difficulties with getSelectedValues method

someone can explain what's wrong in this code ? I'm trying to copy data from a JList to another JList. I would like to know, how and why...

public class Ex3 extends JFrame{
    private JList lista;
    private JList listaCopia;
    private static final String[] cores ={"Azul","Verde","Amarelo"};
    private static final  Color[] cor ={Color.blue,Color.green,Color.yellow};
    private JButton copiar; 

    public Ex3(){
        super("Utilizando JList");
        copiar = new JButton(" Copiar >>>> ");
        lista = new JList<String>(cores);
        setLayout(new FlowLayout());
        lista.setVisibleRowCount(3); // definida linhas visíveis
        lista.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); // método de seleção única de opções
        add(lista);     
        add(copiar);
        copiar.addActionListener(           
                new ActionListener() {          
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        listaCopia.setListData(lista.getSelectedValuesList().toArray());                      
                    }
            });             
        lista.addListSelectionListener(new ListSelectionListener() {            
            @Override
            public void valueChanged(ListSelectionEvent e) {
                getContentPane().setBackground(cor[lista.getSelectedIndex()]);

            }
        });
        listaCopia = new JList<String>();
        listaCopia.setVisibleRowCount(3);
        listaCopia.setFixedCellWidth(100);
        listaCopia.setFixedCellHeight(15);
        add(new JScrollPane(listaCopia));       
    }
}

I found the way here Java - Deprecated method - What to do? but don't explain... I compile another code just using getSelectedValuesList(), and don't worked... why ?

Upvotes: 1

Views: 2663

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209052

Seems to work for me. When I shift/select all items and click the copiar button, all they items from the left get copied to the one on the right. Isn't that what you want?

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class Ex3 extends JFrame {

    private JList lista;
    private JList listaCopia;
    private static final String[] cores = {"Azul", "Verde", "Amarelo"};
    private static final Color[] cor = {Color.blue, Color.green, Color.yellow};
    private JButton copiar;
    DefaultListModel model;

    public Ex3() {
        super("Utilizando JList");
        copiar = new JButton(" Copiar >>>> ");

        lista = new JList(cores);
        setLayout(new FlowLayout());
        lista.setVisibleRowCount(3); // definida linhas visíveis
        lista.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); // método de seleção única de opções
        add(lista);
        add(copiar);
        copiar.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                       listaCopia.setListData(lista.getSelectedValuesList().toArray());
                    }
                });
        lista.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                getContentPane().setBackground(cor[lista.getSelectedIndex()]);

            }
        });
        listaCopia = new JList<String>();
        listaCopia.setVisibleRowCount(3);
        listaCopia.setFixedCellWidth(100);
        listaCopia.setFixedCellHeight(15);
        add(new JScrollPane(listaCopia));
    }

    private static void createAndShowGui() {
        Ex3 frame = new Ex3();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

    }


    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

If you just want to add one element at a time. You should use a ListModel. Here's changes I made for that

public class Ex3 extends JFrame {

    private JList lista;
    private JList listaCopia;
    private static final String[] cores = {"Azul", "Verde", "Amarelo"};
    private static final Color[] cor = {Color.blue, Color.green, Color.yellow};
    private JButton copiar;
    DefaultListModel model;          <-- DefaultListModel

    public Ex3() {
        super("Utilizando JList");
        copiar = new JButton(" Copiar >>>> ");

        lista = new JList(cores);
        setLayout(new FlowLayout());
        lista.setVisibleRowCount(3); // definida linhas visíveis
        lista.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); // método de seleção única de opções

        add(lista);
        add(copiar);

        listaCopia = new JList<String>();
        listaCopia.setVisibleRowCount(3);
        listaCopia.setFixedCellWidth(100);
        listaCopia.setFixedCellHeight(15);
        add(new JScrollPane(listaCopia));

        model = new DefaultListModel();         <-- initialize model
        listaCopia.setModel(model);             <-- set model

        copiar.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                       //listaCopia.setListData(lista.getSelectedValuesList().toArray());
                       model.addElement(lista.getSelectedValue());   <-- Add to model
                    }
                });
        lista.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                getContentPane().setBackground(cor[lista.getSelectedIndex()]);

            }
        });

    }

You can see the <--s where I've added the model and add an element to the model.


Edit:

"I compile another code just using getSelectedValuesList(), and don't worked... why ?"

getSelectedValuesList() returns a List and setListData requires an array argument passed. Also when you setListData you are not able to just change add one item at a time. For that you need to use the model.

See setListData() javadoc | getSelectedValuesList() javadoc

Upvotes: 2

Related Questions