2016-04-14 82 views
0

我必須爲我的Swing項目設計一個fleetmanagment我創建了一個添加按鈕,但我無法弄清楚必須使刪除按鈕的任何幫助嗎?這是我的代碼爲addbutton。Swing - 添加按鈕JList

addbutton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent event) { 
      //make sure you preserve the previously selected list items 
      int size = rightlist.getModel().getSize(); 
      Set objects = new LinkedHashSet(); 
      for (int i = 0; i < size; i++) { 
       objects.add(rightlist.getModel().getElementAt(i)); 
      } 
      objects.addAll(Arrays.asList(leftlistfreight.getSelectedValues())); 

      rightlist.setListData(objects.toArray()); 
     } 
    }); 

編輯!

的ArrayList代碼

List<FreightBoats> freightBoat = new ArrayList<FreightBoats>(); 
    freightBoat.add(new FreightBoats("Boat Name : Stefan |","This Boat can Carry Conitainer : ",25000)); 
    freightBoat.add(new FreightBoats("Boat Name : Sminroff |","This Boat can Carry Conitainer : ",30000)); 
    freightBoat.add(new FreightBoats("Boat Name : Container 2000 |","This Boat can Carry Conitainer : ",2500)); 
    freightBoat.add(new FreightBoats("Boat Name : Windows |","This Boat can Carry Conitainer : ",25200)); 
    freightBoat.add(new FreightBoats("Boat Name : Unhuman |","This Boat can Carry Conitainer : ",200)); 
    freightBoat.add(new FreightBoats("Boat Name : ElPolako |","This Boat can Carry Conitainer : ",300000)); 
    freightBoat.add(new FreightBoats("Boat Name : BrainDead |","This Boat can Carry Conitainer : ",10000)); 
    freightBoat.add(new FreightBoats("Boat Name : WSHR | ","This Boat can Carry Conitainer : ",34005)); 
    freightBoat.add(new FreightBoats("Boat Name : Grolsch ","This Boat can Carry Conitainer : ",10565 

回答

1

不要使用數組或打的ArrayList。不需要使用setListData()方法重新創建ListModel。

取而代之的更新應該直接完成ListModel

閱讀How to Use Lists上的Swing教程部分。 ListDemo示例向您展示瞭如何使用「Hire」和「Fire」按鈕從ListModel「添加」和「刪除」項目。

+0

我想我需要使用ArrayList beacouse我保持我的船名在一個數組中。我把數組代碼。檢查出來,告訴我是否有另一種替代方案可以使用。謝謝 –

+1

@JohnJohnson,'我想我需要使用ArrayList beacouse,我把我的船名保存在一個數組中。' - 不,你不知道。你的應用程序的設計是錯誤的。如果您在JList中顯示數據,則數據存儲在ListModel中。不需要單獨的數組。 '如果還有其他選擇' - Swing組件的設計和使用基於模型 - 視圖 - 控制器設計。我已經提出了適當的解決方案,並指出了一個可行的例子。使用單獨的數組違背了這個設計原則。陣列不需要。 ListModel有訪問數據的方法。 – camickr