在Java Swing中使用JLists

时间:2014-10-29 20:46:48

标签: java swing jlist defaultlistmodel

我必须与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 个答案:

答案 0 :(得分:4)

当您添加到JList时,您希望将其添加到ListModel而非直接添加:

DefaultListModel tempModel = (DefaultListModel) cartList.getModel();
for (String s: BooksList.getSelectedValuesList())
    tempModel.addElement(s);

我还没有机会对此进行测试,但这是正确的做法。目前,您正在调用.setListData(),这会清除其中的内容并替换它。这将为其添加一些内容。

您可能会发现this question有帮助。