简体   繁体   English

向Jlist添加元素

[英]add an element to Jlist

I have two JList s. 我有两个JList

List A has these elements: 列表A具有以下元素:

  • 1 1
  • two
  • 78 78
  • item4 ITEM4

List B that is for now empty. 列表B目前为空。

My frame has these two list and a button Verify . 我的相框有这两个列表和一个按钮Verify Once I click on the button, the selected item of List A gets verified whether it is an integer. 单击按钮后,将验证列表A的选定项是否为整数。 If so, the selected item has to be transfered to List B and removed from List A. 如果是这样,则必须将所选项目转移到列表B并从列表A中删除。

What I did so far is when clicking on the button, the item get copied but once I selected another item the previous one get replaced with the new item which I don't want. 到目前为止,我所做的是单击该按钮时,该项目被复制,但是一旦选择了另一个项目,以前的项目将被我不想要的新项目替换。

How can transfer (append) the item to the other list and remove it from the first one, this way I have got finally the list with all the items without being replaced by the new items. 如何将项目转移(附加)到另一个列表并将其从第一个列表中删除,这样我就可以最终获得所有项目的列表,而不必被新项目替换。

Use a DefaultListModel . 使用DefaultListModel

DefaultListModel dlmA = new DefaultListModel(); // For list A
dlmA.addElement(1);
dlmA.addElement("two");
dlmA.addElement(78);
dlmA.addElement("item4");

listA.setModel(dlmA);

Now, the same for your list B. 现在,您的列表B同样如此。

DefaultListModel dlmB = new DefaultListModel(); // For list B
listB.setModel(dlmB);

If you want to add items to your second list, just add them to the DefaultListModel dlmB . 如果要将项目添加到第二个列表,只需将其添加到DefaultListModel dlmB This means you have to keep a reference to dlmB in your working class, this way you can add elements to it inside the ActionListener of your button. 这意味着您必须在工作类中保留对dlmB的引用,这样便可以在按钮的ActionListener中向其中添加元素。

public void actionPerformed(ActionEvent evt)
{
    // Perform your checks. If you want to add it to list B, use:
    dlmB.addElement(yourNewElem);
}

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

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