2014-10-29 56 views
0

我有JList的一個項目工作,我堅持要做的幾件事情。 這裏是我的清單:使用JList的在的Java Swing

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

以何種方式,你被卡住?你有錯誤嗎? – APerson 2014-10-29 20:51:00

+0

對於1我必須要能夠多次添加到cartList從BooksList和做一次一個,但如果我嘗試添加的所有項目一次一個會刪除該項目的cartList和容下在 新項目2和3他們只是不工作。當項目被點擊沒有任何反應 – ghost1349 2014-10-29 20:53:31

+1

這一信息添加到您的* *的問題沒有意見,因爲這是你離開了你的問題留相當不完整的關鍵信息。 – 2014-10-29 20:55:02

回答

4

當您添加到JList,你想將它添加到其直接ListModel而不是:

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

我還沒有機會測試,但這是正確的做法。目前,您打電話給.setListData(),清除那裏的內容並將其替換。這將增加一些東西來代替。

您可能會發現this question幫助。