简体   繁体   中英

How to Add Element to JList in swing?

Hi i am newbie to java and i am trying to add the item from JComboBox to the JList , but when i run the program, i am getting this error.

How to do this?

error:

cannot find symbol
symbol  : method addElement(java.lang.String)
location: class javax.swing.JList
      openTaskBox.addElement(taskItem);

code:

public static void addSelectedItemToTaskList(String taskItem)
   {
      openTaskBox.addElement(taskItem);
   }

Here openTaskBox is JList .

Code:

    JList openTaskBox = new JList();
    openTaskBox.setPreferredSize(new Dimension(350, 50));
    pnlInnerTL.add(openTaskBox);

Add the item to the JList 's model, not to the JList itself.

DefaultListModel model = (DefaultListModel) openTaskBox.getModel();
model.addElement(taskItem);

For JComboBox

You can use JComboBox#addItem(E)

See How to use Combo Boxes for more details

For JList

You have to use the ListModel . DefaultListModel supplies a addElement method

See How to use lists for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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