简体   繁体   English

如何将多行从TextField添加到JList

[英]How to add multiple line from TextField to JList

I have the following code : 我有以下代码:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    Tname = name.getText();

    DefaultListModel model;
    model = new DefaultListModel();
    model.addElement(Tname);
    list.setModel(model);
}         

When I try this code, and add text from TextField, and show in Jlist, it always replace previous line with new one. 当我尝试此代码并添加TextField中的文本并在Jlist中显示时,它总是将上一行替换为新行。

How can I add multiple line without replacing previous input? 如何添加多行而不替换先前的输入?

You're creating a new DefaultListModel every time this method is called, and so you're removing all data held by the original list model. 每次调用此方法时,您都将创建一个新的 DefaultListModel,因此将删除原始列表模型中保存的所有数据。 The solution is not to do this. 解决方案是不这样做。 Get the current ListModel from your JList, don't create a new one, and then add your element to the current ListModel. 从您的JList中获取当前的ListModel, 不要创建一个新的ListModel,然后将您的元素添加到当前的ListModel中。 That's it. 而已。

ie,

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // Tname       =   name.getText(); // *** follow Java naming rules please
    String tName = name.getText();

    DefaultListModel model = (DefaultListModel) list.getModel();
    model.addElement(tName);
}

Don't call setModel(...) when you do this since you're already using the current model. 执行此操作时请勿调用setModel(...) ,因为您已经在使用当前模型。

That is happening because of this: 发生这种情况的原因是:

DefaultListModel model;
model = new DefaultListModel();

every time you execute this lines, you create a new object, so the old information in the list is gone, 每次执行此行时,您都会创建一个新对象,因此列表中的旧信息消失了,

instead initialize the model in the constructor and use the jButton1ActionPerformed only for adding the elements. 而是在构造函数中初始化模型,并仅将jButton1ActionPerformed用于添加元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM