Java 在模型中更新ArrayList时,应在视图中更新JLList

Java 在模型中更新ArrayList时,应在视图中更新JLList,java,swing,model-view-controller,arraylist,jlist,Java,Swing,Model View Controller,Arraylist,Jlist,我已经玩了一段时间了,但没有成功。我已经看过ListModel,但很难在我当前的项目中实现它 我有一个生产者类线程向模型中的ArrayList添加元素。这工作正常,ArrayList正在运行时更新。我的问题是,然后我想将添加到ArrayList的新对象添加到View类中的JLList。我看不到如何将ListModel或DefaultListModel导入当前设置。非常感谢你的帮助 public class Person { private String name; private

我已经玩了一段时间了,但没有成功。我已经看过ListModel,但很难在我当前的项目中实现它

我有一个生产者类线程向模型中的ArrayList添加元素。这工作正常,ArrayList正在运行时更新。我的问题是,然后我想将添加到ArrayList的新对象添加到View类中的JLList。我看不到如何将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();
    }
}
公共类人物
{
私有字符串名称;
私人互联网;
公众人物(字符串名称,整数年龄)
{
this.name=名称;
这个。年龄=年龄;
}
公共字符串getName()
{
返回名称;
}
公共整数getAge()
{
回归年龄;
}
公共字符串toString()
{
返回此.name;
}
}
公共类生产者扩展线程
{
私有模型;
公共生产者(模型)
{
this.model=模型;
}
公开募捐
{
人fred=新人(“fred Flintstone”,37);
人物威尔玛=新人(“威尔玛·弗林斯通”,18);
人卵石=新人(“卵石燧石”,15);
人物恐龙=新人(“恐龙燧石”,45);
人巴尼=新人(“巴尼瓦砾”,76);
人物贝蒂=新人(“贝蒂·瓦砾”,76);
人员bamm=新人员(“bamm bamm碎石”,76);
尝试
{
范德佩森(弗雷德);
睡眠(1500);
型号:addPerson(威尔玛);
睡眠(1500);
模型。addPerson(卵石);
睡眠(1500);
型号:addPerson(迪诺);
睡眠(1500);
模型。addPerson(巴尼);
睡眠(1500);
模特艾德佩森(贝蒂);
睡眠(1500);
model.addPerson(bamm);
}
捕获(例外e)
{
System.out.println(“将Person对象添加到Model.people时出错
ArrayList“+e);
}
}
}
公共类模型
{
私人名单;
公共模型()
{
people=newarraylist();
}
公共列表getPeople()
{
还人,;
}
公共无效添加人(人/人)
{
人。加(人);
System.out.println(“添加到人员列表的人员对象:“+aPerson”);
}
公共无效删除人(个人)
{
人。移走(人);
}
}
公共类视图扩展了JFrame
{
私人JPanel topPanel,botPanel;
私家侦探;
私有JScrollPane滚动窗格;
私有模型;
公共视图(模型)
{
this.model=模型;
设置大小(200220);
设置标题(“视图”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
topPanel=新的JPanel();
botPanel=newjpanel();
peopleList=newjlist(model.getPeople().toArray());
scrollPane=新的JScrollPane(peopleList);
topPanel.setLayout(新网格布局(1,1));
添加(滚动窗格);
topPanel.setBorder(BorderFactory.createTitledBorder
(BorderFactory.createEtchedBorder(),“人员列表”);
容器cp=getContentPane();
cp.add(topPanel,BorderLayout.NORTH);
cp.add(botPanel,BorderLayout.SOUTH);
}
}
公共班机
{
公共静态void main(字符串[]args)
{
模型=新模型();
视图视图=新视图(模型);
theView.setVisible(true);
生产者=新生产者(模型);
producer.start();
}
}

在此处使用适当的MVC模式:视图侦听模型中的更改,并根据模型中的通知进行更新:

  • 在模型上添加
    PropertyChangeSupport
    ,并在修改模型时触发
    PropertyChangeEvent
  • 将视图添加为模型的
    属性ChangeListener
  • 相应地对通知作出反应(如果
    人员
    添加到您的模型中,当您收到显示“新增人员”的事件时,将其添加到
    人员列表的
    列表模型
    ,与“已删除人员”相同,等等。)
  • 注意:由于您的模型将被EDT(事件调度线程)以外的另一个线程修改,请确保您在EDT上修改了UI(查看
    SwingUtilities.isEventDispatchingThread()
    SwingUtilities.invokeLater()

    更新:

    下面是一个片段,它演示了我试图在上面解释的内容(如果有点长,很抱歉,但我试图尽可能接近您的原始代码):

    导入java.awt.BorderLayout;
    导入java.awt.Container;
    导入java.awt.GridLayout;
    导入java.beans.PropertyChangeEvent;
    导入java.beans.PropertyChangeListener;
    导入java.beans.PropertyChangeSupport;
    导入java.util.ArrayList;
    导入java.util.List;
    导入java.util.Random;
    导入javax.swing.BorderFactory;
    导入javax.swing.DefaultListModel;
    导入javax.swing.JFrame;
    导入javax.swing.JList;
    导入javax.swing.JPanel;
    导入javax.swing.JScrollPane;
    导入javax.swing.SwingUtilities;
    公共班机{
    公共阶层人士{
    私有字符串名称;
    私人互联网;
    公众人物(字符串名称,整数年龄){
    this.name=名称;
    这个。年龄=年龄;
    }
    公共字符串getName(){
    返回名称;
    }
    公共整数getAge(){
    回归年龄;
    }
    @凌驾
    公共字符串toString(){
    返回此.name;
    }
    }
    公共类生产者扩展线程{
    私有模型;
    公共生产者(模型){
    this.model=模型;
    }
    @奥夫
    
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.GridLayout;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyChangeSupport;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    
    import javax.swing.BorderFactory;
    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    
    public class Main {
    
        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;
            }
    
            @Override
            public String toString() {
                return this.name;
            }
        }
    
        public class Producer extends Thread {
            private Model model;
    
            public Producer(Model model) {
                this.model = model;
            }
    
            @Override
            public void run() {
                Random random = new Random();
                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);
                while (true) {
                    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);
                        while (model.getPeople().size() > 0) {
                            Person p = model.getPeople().get(random.nextInt(model.getPeople().size()));
                            model.removePerson(p);
                            Thread.sleep(1000);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        public class Model {
            private static final String PEOPLE = "people";
    
            private List<Person> people;
    
            private PropertyChangeSupport propertyChangeSupport;
    
            public Model() {
                people = new ArrayList<Person>();
                propertyChangeSupport = new PropertyChangeSupport(this);
            }
    
            public PropertyChangeSupport getPropertyChangeSupport() {
                return propertyChangeSupport;
            }
    
            public List<Person> getPeople() {
                return people;
            }
    
            public void addPerson(Person aPerson) {
                people.add(aPerson);
                System.out.println("Person object added to people list:" + aPerson);
                getPropertyChangeSupport().firePropertyChange(PEOPLE, null, aPerson);
            }
    
            public void removePerson(Person aPerson) {
                people.remove(aPerson);
                getPropertyChangeSupport().firePropertyChange(PEOPLE, aPerson, null);
            }
        }
    
        public class View extends JFrame implements PropertyChangeListener {
            private JPanel topPanel, botPanel;
            private JList peopleList;
            private JScrollPane scrollPane;
            private Model model;
            private DefaultListModel peopleListModel;
    
            public View(Model model) {
                this.model = model;
                setSize(200, 220);
                setTitle("View");
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                topPanel = new JPanel();
                botPanel = new JPanel();
                peopleListModel = new DefaultListModel();
                for (Person p : model.getPeople()) {
                    peopleListModel.addElement(p);
                }
                peopleList = new JList(peopleListModel);
                model.getPropertyChangeSupport().addPropertyChangeListener(Model.PEOPLE, this);
                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);
            }
    
            @Override
            public void propertyChange(final PropertyChangeEvent evt) {
                if (!SwingUtilities.isEventDispatchThread()) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            propertyChange(evt);
                        }
                    });
                    return;
                }
                if (evt.getSource() == model) {
                    if (Model.PEOPLE.equals(evt.getPropertyName())) {
                        if (evt.getOldValue() != null && evt.getNewValue() == null) {
                            peopleListModel.removeElement(evt.getOldValue());
                        } else if (evt.getOldValue() == null && evt.getNewValue() != null) {
                            peopleListModel.addElement(evt.getNewValue());
                        }
                    }
                }
            }
        }
    
        public static void main(String[] args) {
            new Main().init();
        }
    
        private void init() {
            final Model model = new Model();
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    View theView = new View(model);
                    theView.setVisible(true);
                }
            });
            Producer producer = new Producer(model);
            producer.start();
        }
    }