我已经玩了一段时间了,但没有成功。我看过 ListModel 但一直在努力将它实施到我当前的项目中。
我有一个生产者类线程将元素添加到模型中的 ArrayList。这工作正常,并且 ArrayList 正在运行时更新。我的问题是,然后我希望将添加到 ArrayList 的新对象添加到 View 类中的 JList 中。我看不到如何将 ListModel 或 DefaultListModel 合并到我当前的设置中。非常感谢帮助。
public class Person
{
private String name;
private int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return this.name;
}
}
public class Producer extends Thread
{
private Model model;
public Producer(Model model)
{
this.model = model;
}
public void run()
{
Person fred = new Person("Fred Flintstone", 37);
Person wilma = new Person("Wilma Flintstone", 18);
Person pebbles = new Person("Pebbles Flintstone", 15);
Person dino = new Person("Dino Flintstone", 45);
Person barney = new Person("Barney Rubble", 76);
Person betty = new Person("Betty Rubble", 76);
Person bamm = new Person("Bamm-Bamm Rubble", 76);
try
{
model.addPerson(fred);
Thread.sleep(1500);
model.addPerson(wilma);
Thread.sleep(1500);
model.addPerson(pebbles);
Thread.sleep(1500);
model.addPerson(dino);
Thread.sleep(1500);
model.addPerson(barney);
Thread.sleep(1500);
model.addPerson(betty);
Thread.sleep(1500);
model.addPerson(bamm);
}
catch(Exception e)
{
System.out.println("Error adding Person object to Model.people
ArrayList" + e);
}
}
}
public class Model
{
private List <Person> people;
public Model()
{
people = new ArrayList<Person>();
}
public List<Person> getPeople()
{
return people;
}
public void addPerson(Person aPerson)
{
people.add(aPerson);
System.out.println("Person object added to people list:" + aPerson);
}
public void removePerson(Person aPerson)
{
people.remove(aPerson);
}
}
public class View extends JFrame
{
private JPanel topPanel, botPanel;
private JList peopleList;
private JScrollPane scrollPane;
private Model model;
public View(Model model)
{
this.model = model;
setSize(200, 220);
setTitle("View");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
topPanel = new JPanel();
botPanel = new JPanel();
peopleList = new JList(model.getPeople().toArray());
scrollPane = new JScrollPane(peopleList);
topPanel.setLayout(new GridLayout(1, 1));
topPanel.add(scrollPane);
topPanel.setBorder(BorderFactory.createTitledBorder
(BorderFactory.createEtchedBorder(), "People list"));
Container cp = getContentPane();
cp.add(topPanel, BorderLayout.NORTH);
cp.add(botPanel, BorderLayout.SOUTH);
}
}
public class Main
{
public static void main(String[] args)
{
Model model = new Model();
View theView = new View(model);
theView.setVisible(true);
Producer producer = new Producer(model);
producer.start();
}
}