2014-10-06 59 views
-1

我有一個使用JTabbedPane的程序。在一個窗格上,我有一個按鈕,根據來自同一窗格的輸入更新對象的arrayList。如何在兩個單獨的JTabbedPanes之間傳遞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); 

    } 
} 

} 
+0

確實有辦法。你爲什麼不發佈你的代碼,以便我們可以看到你正在使用的是什麼? – ControlAltDel 2014-10-06 19:15:03

+0

已發佈代碼。我遺漏了所有的GUI設置@ControlAltDel – jrounsav 2014-10-06 19:33:59

+1

解決此問題的最佳方法是使用1類中的現成Swing/etc組件來設置和控制它們。這樣,如果您的列表發生更改,您可以在可訪問所有內容的頂層處理您需要完成的操作 – ControlAltDel 2014-10-06 19:42:31

回答

0

可以使用用於更新的第一個ArrayList中,相同的偵聽器來更新第二個窗格爲每個對象一個複選框框。例如:

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