如何在两个单独的JTabbedPanes之间传递ArrayList

时间:2014-10-06 19:06:42

标签: java oop arraylist jtabbedpane

我有一个使用JTabbedPane的程序。在一个窗格中,我有一个按钮,可以根据同一窗格的输入更新对象的arrayList。

我想要发生的是让第二个窗格更新自身,并根据第一个窗格中的arrayList更新对象信息。

但是,我不确定如何在窗格之间传递列表。当按下第一个窗格上的更新按钮时,是否有某种方法将阵列推送到窗格#2?

这是主文件。实例化两个标签

public class Assignment6 extends JApplet
 {

   private int APPLET_WIDTH = 650, APPLET_HEIGHT = 350;

   private JTabbedPane tPane;
   private StorePanel storePanel;
   private PurchasePanel purchasePanel;
   private ArrayList computerList;


   public void init()
    {

     computerList = new ArrayList();


     storePanel = new StorePanel(computerList, purchasePanel);
     purchasePanel = new PurchasePanel(computerList);




     tPane = new JTabbedPane();
     tPane.addTab("Store Inventory", storePanel);
     tPane.addTab("Customer Purchase", purchasePanel);

     getContentPane().add(tPane);
     setSize (APPLET_WIDTH, APPLET_HEIGHT); //set Applet size
    }
}

第一个面板实例化一个按钮监听器,它将所有逻辑应用于数组列表" compList"

private class ButtonListener implements ActionListener
   {
    public void actionPerformed(ActionEvent event)
     {
                //Add Computer to list
                Computer comp = new Computer();
                comp.setBrandName(brandField.getText());
                comp.setPrice(Double.parseDouble(priceField.getText()));
                comp.setMemory(Integer.parseInt(memoryField.getText()));
                comp.setCPU(typeField.getText(), Integer.parseInt(speedField.getText()));

                compList.add(comp);
                }
                stringField.setText(listString);


                alertLabel.setText("Computer Added");
            }
        }

这是另一个窗格。最后的for循环是我需要将arrayList推送到的。收到列表后,它会填充一个框,其中包含列表中每个对象的复选框

public PurchasePanel(ArrayList compList)
{
  west = new JPanel();
  east = new JPanel();
  totalField = new JTextField();

  this.compList = compList;
  setLayout(new GridLayout(0,2));
  add(west);
  add(east);
  east.setLayout(new BorderLayout());
  east.add(currentTotalLabel, BorderLayout.NORTH);
  east.add(totalField, BorderLayout.CENTER);
  west.setLayout( new BoxLayout(west, BoxLayout.Y_AXIS));

  for(Object c : compList){
      System.out.println("Made it");

      NumberFormat fmt = NumberFormat.getCurrencyInstance();

      String str = ("BrandName:" + (((Computer) c).getBrandName() +"CPU:" + (((Computer) c).getCPU() +"Memory:" + ((Computer) c).getMemory() + "M" +"Price:" + fmt.format(((Computer) c).getPrice()))));


      JCheckBox chk = new JCheckBox(str);
      west.add(chk);

    }
}

 }

1 个答案:

答案 0 :(得分:0)

您可以使用用于更新第一个ArrayList的相同侦听器来更新第二个窗格。类似的东西:

jButton1.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) { 
        // Update the first ArrayList
        // Update the second pane
    }