简体   繁体   中英

Moving a String from one JList To Another

I can't figure out how to transfer a string from one JList to another. there is another class with the main but that only creates the JFrame for the buttons to be on. I tried do rightList.setListData(leftList.getSelectedValues but it crossed out the getSelectedValues

package multiList;

import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.Vector;

import javax.swing.*;
import javax.swing.event.*;

public class Gui extends JFrame {
    private JList leftList;
    private JList rightList;
    private JButton moveButton;
    private static String[] food = {"Pizza", "Spagetiti", "Mac and Cheese", "Cheese", "MorePizza"};

    public Gui() {
        super("title");
        setLayout(new FlowLayout());

        leftList = new JList(food);
        leftList.setVisibleRowCount(3);
        leftList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        add(new JScrollPane(leftList));

        moveButton = new JButton("Move ---->");
        moveButton.addActionListener(
                new ActionListener() {
                    @SuppressWarnings("deprecation")
                    public void ActionPreformed(ActionEvent event) {
                        rightList.setListData(leftList.getSelectedValues());
                    }

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        // TODO Auto-generated method stub
                    }
                }
        );

        add(moveButton);

        rightList = new JList();
        rightList.setVisibleRowCount(3);
        rightList.setFixedCellWidth(100);
        rightList.setFixedCellHeight(15);
        rightList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        add(new JScrollPane(rightList));
    }
}

This should work:

DefaultListModel model = (DefaultListModel) leftList.getModel();
DefaultListModel list2Model = new DefaultListModel();
int[] selected = leftList.getSelectedIndices();
for (int i = 0; i < selected.length; i++) {
         list2Model.addElement(model.elementAt(i));
    }

rightList.setModel(list2Model);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM