我必须为项目使用JLists,但我坚持尝试做几件事。
这是我的清单:
JList<String> BooksList = new JList<String>(booksList);
books.add(BooksList, BorderLayout.CENTER);
BooksList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JList cartList = new JList();
cart.add(cartList, BorderLayout.CENTER);
cartList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
在BooksList中有以下各项:
I Did It Your Way;11.95
The History of Scotland;14.50
Learn Calculus in One Day;29.95
Feel the Stress;18.50
Great Poems;12.95
Europe on a Shoestring;10.95
The Life of Mozart;14.50
1.)将项目从BooksList移到cartList,特别是我需要它来添加新添加的项目,但是如果我尝试一次添加一个项目,则它将用新项目替换cartList中已经存在的项目。这是我的代码:
//Adding To Cart
JButton AddToCart = new JButton("Add To Cart");
AddToCart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ArrayList<String> selectionList = (ArrayList<String>) BooksList.getSelectedValuesList();
Object[] selections = selectionList.toArray();
cartList.setListData(selections);
}
});
AddToCart.setToolTipText("Alt + A For Auto Add");
AddToCart.setBounds(264, 178, 117, 25);
AddToCart.setMnemonic(KeyEvent.VK_A);
frame.getContentPane().add(AddToCart);
2.)完全清除购物车列表,由于某种原因,单击此按钮后无任何反应。这是代码:
//This Will Clear The Whole Cart List
JMenuItem Clear = new JMenuItem("Clear Alt + C");
cartMenu.add(Clear);
Clear.setMnemonic(KeyEvent.VK_C);
Clear.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
DefaultListModel tempModel = (DefaultListModel)cartList.getModel();
tempModel.removeAllElements();
}
});
3.)删除选定的项目,与2相同的是它什么都不做。我有以下代码:
//Remove A Selected Item From The List
JMenuItem RemoveSelected = new JMenuItem("Remove Selected Alt + R");
cartMenu.add(RemoveSelected);
RemoveSelected.setMnemonic(KeyEvent.VK_R);
RemoveSelected.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent e) {
DefaultListModel tempModel = (DefaultListModel)cartList.getModel();
int selected = cartList.getSelectedIndex();
if(selected != -1)
{
tempModel.remove(selected);
}
}
});
最佳答案
当添加到JList
时,您想将其添加到其ListModel
而不是直接添加:
DefaultListModel tempModel = (DefaultListModel) cartList.getModel();
for (String s: BooksList.getSelectedValuesList())
tempModel.addElement(s);
我没有机会进行测试,但这是正确的方法。当前,您正在调用
.setListData()
,它将清除其中的内容并将其替换。这将为其添加一些内容。您可能会发现this question有帮助。