我想要的是,当用户点击按钮时,在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());
}
我尝试打印出数组的内容,看是否记录了用户输入,但是没有打印出来。
答案 0 :(得分:1)
代码的问题是,只要用户单击“确定”按钮,就会执行actionPerformed(ActionEvent)方法。每次调用该方法时,您都要创建一个ArrayList,它不包含以前的选择。因此,ArrayList必须是一个实例变量。每次用户单击“确定”按钮时,只需将选择添加到列表中即可。
答案 1 :(得分:0)
您需要在ActionListener
之外保留List 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());
}
答案 2 :(得分: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());
}
}