0

我想要的是,当用户单击按钮时,输入或从任何地方删除的数据进入Textbox数组JList列表。

我不想建数据库!我只想在用户使用应用程序时存储数据。什么都试过了,好像事件按钮有一定的难度,代码不要太认真,只是用来分析的。

重要的是通过按下按钮将数据写入数组。前任:

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());   
    }

我试图打印出数组的内容,以查看是否记录了用户输入,但它没有打印出任何内容。

4

3 回答 3

1

您的代码的问题是,每当用户单击“确定”按钮时,您的 actionPerformed(ActionEvent) 方法就会被执行。每次调用该方法时,您都会创建一个 ArrayList,其中不包含先前的选择。所以,ArrayList 必须是一个实例变量。每次用户单击确定按钮时,您只需将选择添加到列表中。

于 2013-09-26T17:18:50.240 回答
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());  
  }
于 2013-09-26T16:57:57.287 回答
0

您应该在动作侦听器之外建立 arraylist,并且只在侦听器内部执行 add 函数,如下所示:

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());
    }

}
于 2013-09-26T17:03:34.940 回答