我正在研究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);
}
}
答案 0 :(得分:0)
null
LayoutManager
。阅读下一个tutorial。对于填充值,请使用下一个代码:
for (int i = 0; i < myList.size(); i++) {
values[i] = myList.get(i).getFirstName();
}
您需要JList
的自定义模型,只需使用值构造函数创建JList
:
JList<String> list = new JList<String>(values);
另请阅读JList
tutorial