JList和ArrayList的更新 [英] JList and ArrayList update

查看:182
本文介绍了JList和ArrayList的更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有例子就如何当我从一个ArrayList中添加或删除元素更新一个JList,

I would like to have example on how to update a JList when I add or remove elements from a ArrayList.

在ArrayList是模型类的一部分。模型类传递给视图(这是包含几个Swing组件一个JPanel,而我想更新JList中),通过它的构造。模型类也注入在一类读取从服务器接收到的值。当我从服务器接收到的数据我想补充一些人对我的ArrayList做model.getArrayList()。添加(数据)。当我添加数据到ArrayList我想在我看来,以更新的JList。我想就如何我的ArrayList与我联系JList的帮助。

The ArrayList is part of Model class. The Model class is passed to the view (which is a JPanel containing several swing components, and the JList I want to update) via its constructor. The model class is also injected in a class that reads values received from the server. When i received data from the server I add some of them to my arrayList by doing model.getArrayList().add(data). When I add data to the arrayList i would like to update the JList in my view. I would like to have help on how to link my ArrayList with my JList.

推荐答案

如果您创建自己的 ListModel的你应该继承的 的AbstractListModel 并实施当你的的addElement 方法,你需要调用一个 -method(通知用于更新的用户界面),如:

If you create your own ListModel you should extend AbstractListModel and when implementing your addElement method, you need to call a fire-method (for notifying the user interface for the update), like:

public void addElement(MyObject obj) {
    myArrayList.add(obj);
    fireIntervalAdded(this, myArrayList.size()-1, myArrayList.size()-1);
}

您的自定义ListModel的应该是这个样子:

You custom ListModel should look something like this:

public class MyListModel extends AbstractListModel {

    private final ArrayList<MyObject> myArrayList = new ArrayList<MyObject>();

    public void addElement(MyObject obj) {
        myArrayList.add(obj);
        fireIntervalAdded(this, myArrayList.size()-1, myArrayList.size()-1);
    }

    @Override
    public Object getElementAt(int index) { return myArrayList.get(index); }

    @Override
    public int getSize() { return myArrayList.size(); }
}

这篇关于JList和ArrayList的更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆