如何遍历ArrayList并仅从每个对象中提取1个字段

时间:2014-11-04 20:25:34

标签: java swing arraylist iterator jlist

我正在研究JList问题。我有一个对象的数组列表,每个有3个字段。我想将lastName,firstName放在JList中,但只能弄清楚如何从ArrayList中提取最后的对象信息。

任何帮助将不胜感激。感谢

import java.awt.EventQueue;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.AbstractListModel;

public class TestingListsGUI
{

private JFrame  frame;
String[]        values;

/**
 * Launch the application.
 */
public static void main(String[] args)
{
    EventQueue.invokeLater(new Runnable()
    {
        public void run()
        {
            try
            {
                TestingListsGUI window = new TestingListsGUI();
                window.frame.setVisible(true);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public TestingListsGUI()
{
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize()
{
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    // Create Array list and populate it with generic info for testing
    final List<JListsTesting> myList = new ArrayList<JListsTesting>();

    myList.add(new JListsTesting("Bruce", "James", "Totally Awesome"));
    myList.add(new JListsTesting("Potter", "Harry", "A Magician"));
    myList.add(new JListsTesting("Sanders", "Col", "The Chicken Meister"));
    myList.add(new JListsTesting("Bond", "James", "Licensed to Kill"));

    values = new String[myList.size()];

    for (int i = 0; i < myList.size(); i++)
    {

        values[i] = JListsTesting.getFirstName();

    }

    JList list = new JList();
    list.setModel(new AbstractListModel()
    {

        public int getSize()
        {
            return values.length;
        }

        public Object getElementAt(int index)
        {
            return values[index];
        }
    });

    list.setSelectedIndex(0);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setBounds(33, 23, 236, 249);
    frame.getContentPane().add(list);
}

}

1 个答案:

答案 0 :(得分:0)

  1. 请勿使用null LayoutManager。阅读下一个tutorial
  2. 对于填充值,请使用下一个代码:

    for (int i = 0; i < myList.size(); i++) {
        values[i] = myList.get(i).getFirstName();
    }
    
  3. 您需要JList的自定义模型,只需使用值构造函数创建JList

    JList<String> list = new JList<String>(values);

  4. 另请阅读JList tutorial