java 添加到现有的 JList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16719841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:46:24  来源:igfitidea点击:

Adding to existing JList

javaswingjlistdefaultlistmodel

提问by Máca Danilov

I need some help about adding items to JList. I work on some "library" kind of project. And I need to add readers to already existing JList. But when I try to add it, JList just resets, removes all the readers and starts adding readers to a new blank JList. But I don't need it to make new list but add it to the already existing one.

我需要一些关于向 JList 添加项目的帮助。我从事一些“图书馆”类型的项目。我需要将读者添加到现有的 JList。但是当我尝试添加它时,JList 只是重置、删除所有阅读器并开始将阅读器添加到新的空白 JList。但我不需要它来制作新列表,而是将其添加到现有列表中。

I know it's something about creating new model after adding, but i don't know where to fix it.

我知道这是添加后创建新模型的事情,但我不知道在哪里修复它。

panelHorni = new JPanel();
    listModel = new DefaultListModel();
    listCtenaru = new JList(listModel);

    FileInputStream fis = new FileInputStream("myjlist.bin");
    ObjectInputStream ois = new ObjectInputStream(fis);

    listCtenaru = (JList)ois.readObject();

    listScroll = new JScrollPane();
    listScroll.add(listCtenaru);


    listCtenaru.setPreferredSize(new Dimension(350, 417));
    listCtenaru.setBackground(new Color(238,238,238));

    panelHorni.add(listCtenaru);

listener

听众

 public void actionPerformed(ActionEvent e) {

            String jmeno = pole1.getText();
            String prijmeni = pole2.getText();

            listModel.addElement(jmeno +" "+ prijmeni);
            listCtenaru.setModel(listModel);

            pole1.setText("");
            pole2.setText("");
            pole1.requestFocus();

回答by camickr

listModel.addElement(jmeno +" "+ prijmeni);
//listCtenaru.setModel(listModel);

There is no need to use the setModel() method if you are trying to update the existing model. The fact that you are trying to do this would seen to indicate you are creating a new model instead of updating the existing model.

如果您尝试更新现有模型,则无需使用 setModel() 方法。您尝试执行此操作的事实表明您正在创建新模型而不是更新现有模型。

See the Swing tutorial on How to Use Listsfor a working example that updates the existing model.

有关更新现有模型的工作示例,请参阅有关如何使用列表的 Swing 教程。

回答by Azad

The default model of JListis ListModelyou must firstly change it inside the constructor to DefaultListModel.
That solves your problem:

的默认模型JListListModel您必须首先在构造函数中将其更改为DefaultListModel.
这解决了你的问题:

private JList list ;
private DefaultListModel model;
public ListModelTest(){//default constructor
//....
list = new JList();
model = new DefaultListModel();
list.setModel(model);
//....
}
public void actionPerformed(ActionEvent ev){
 model.addElement("element");
 //....
}