使用SWING从另一个面板的列表中显示所选行索引

时间:2015-06-06 18:54:59

标签: java swing listselectionlistener

我有一个显示元素的列表。我希望每次从列表中选择一个元素,以在另一个JPanel中显示其索引。 代码:

        leftPanel.setLayout(new BoxLayout(leftPanel,BoxLayout.PAGE_AXIS));
        leftList = new JList(listModel);
        leftList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        listScrollPane = new JScrollPane(leftList);
        listScrollPane.setBorder(BorderFactory.createTitledBorder("Proteins"));
        rightPanel.setBackground(Color.magenta);
        rightPanel.setLayout(new FlowLayout());   
        for (String name : allNames) {
            listModel.addElement(name);
        }

        leftList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent event) {
                int nameIndex = leftList.getSelectedIndex();
                JLabel msglabel = new JLabel("index = " + nameIndex, JLabel.CENTER);
                rightPanel.add(msglabel);
            }
        });

这不会在JPanel中显示任何内容

1 个答案:

答案 0 :(得分:0)

在此代码中,当选择一个元素时,可以通过按下按钮移动到另一个列表,检查此代码它将帮助您

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

public class Exp extends JFrame {

private JList rl;
private JList ll;
private JButton b;
private static String[] foods = { "asd", "asd", "dfg", "wer", "tyu" };

public Exp() {
    super("Title");
    setLayout(new FlowLayout());

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

    b = new JButton("Move -->");
    b.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            rl.setListData(ll.getSelectedValues());

        }
    });

    add(b);

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