2013-09-26 56 views
0

我想要的是,當用戶單擊按鈕時,在TextboxJList中輸入的數據或從任何地方移除的數據都會進入數組列表。用JButton JAVA將數據寫入ArrayList

我不想建立數據庫!我只想在用戶使用應用程序時存儲數據。我嘗試過所有的事情,但事件按鈕似乎需要一定的難度,代碼不應該被認真對待,它只是用於分析。

重要的是按下按鈕將數據寫入數組。 例如:

btnSaveToArray.addActionListener (new ActionListener() { 

    public void actionPerformed (ActionEvent e) { 

     ArrayList recordArray=new ArrayList(); 

     // This variable receiveList, receives value a given selected from a JList, is far from good. 
     String receiveList = userList.getSelectedValue().toString(); 
     // The variable recordArray capture this value, the goal is that this variable store it. 
     recordArray.add(receiveList); 

     // these two lines to see if I recorded the same roof but're angry, it just returns me one record element. 
     System.out.println(recordArray.toString()); 
     // these two lines to see if I recorded the same roof but're angry, it just returns me one record element. 
     System.out.println(recordArray.size()); 
    } 

我試圖打印出數組的內容,看是否用戶的輸入被記錄,但它並沒有打印出任何東西。

回答

1

您的代碼的問題是每當用戶點擊確定按鈕時,您的actionPerformed(ActionEvent)方法將被執行。每次調用該方法時,都會創建一個ArrayList,它不包含之前的選擇。所以,ArrayList必須是一個實例變量。每次用戶點擊確定按鈕,您只需將選擇添加到列表中。

+0

感謝兄弟! :) –

+0

歡迎您:) –

0

您需要在列表外保持距離的ActionListener

ArrayList recordArray=new ArrayList(); 

    btnSaveToArray.addActionListener (new ActionListener() { 

     public void actionPerformed (ActionEvent e) { 

     String receiveList = userList.getSelectedValue().toString(); 

     recordArray.add(receiveList); 

     System.out.println(recordArray.toString()); 
     System.out.println(recordArray.size()); 
    } 
+0

THANKS BROOOO !!!! :D –

+0

你是人!謝謝 ! YESS! :D –

+0

高興聽到.......... – Prabhakaran

0

您應該建立動作監聽之外ArrayList中,只有執行監聽器裏的附加功能,如:

public class Recorder { 

    public ArrayList recordArray; 

    public Recorder() { 
     recordArray = new ArrayList(); 
     JButton btnSaveToArray = new JButton.... //whatever you are doing here 
     btnSaveToArray.addActionListener (new ActionListener() { 
      public void actionPerformed (ActionEvent e) { 
       String receiveList = userList.getSelectedValue().toString(); 
       recordArray.add(receiveList); 
       showTheRecords(); 
     }); 
    } 

    public void showTheRecords() { 
     for (int i = 0; i < recordArray.size(); i++) { 
      System.out.println(recordArray.get(i).toString()); //get 
     } 
     System.out.println("Record count: " + recordArray.size()); 
    } 

} 
+0

謝謝兄弟! :) –

+0

@RamomMoura - 沒問題。投票表示感謝,以及;) –