2016-04-14 83 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