2014-11-04 55 views
0

我正在處理JList問題。我有一個對象的數組列表,每個都有3個字段。我想把lastName,firstName放在JList中,但只能弄清楚如何從ArrayList中取出最後一個對象的信息。如何迭代ArrayList,只從每個對象中抽出1個字段

任何幫助,將不勝感激。由於

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); 
} 

} 

回答

0
  1. 不要使用nullLayoutManager。閱讀下一個tutorial
  2. 對於填充值,使用下面的代碼:

    for (int i = 0; i < myList.size(); i++) { 
        values[i] = myList.get(i).getFirstName(); 
    } 
    
  3. 您need't爲JList自定義模型只是創建JList與價值構造:

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

又讀JList tutorial

相關問題