【发布时间】:2014-10-29 20:46:47
【问题描述】:
我必须使用 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);
}
}
});
【问题讨论】:
-
你卡在什么地方了?你有错误吗?
-
对于 1,我必须能够从 BooksList 向 cartList 添加多个并一次完成一个,但如果我尝试一次添加所有项目,它将删除该项目在 cartList 中,只将新项目放入 For 2 和 3 他们只是不工作。单击该项目时没有任何反应
-
将此信息添加到您的 question 中,而不是在 cmets 中,因为这是您在问题中遗漏的关键信息,使其非常不完整。
-
避免使用
null布局,像素完美的布局是现代用户界面设计中的一种错觉。影响组件单个尺寸的因素太多,您无法控制。 Swing 旨在与核心布局管理器一起工作,丢弃这些将导致无穷无尽的问题和问题,您将花费越来越多的时间来尝试纠正
标签: java swing jlist defaultlistmodel