【发布时间】:2022-01-16 19:43:23
【问题描述】:
我是 java 新手,我正在尝试使用 java 为我的最终项目创建一个测验应用程序。每次单击按钮时,我都想将在 textField 中输入的文本添加到我的 ArrayList 中。我尝试制作它,但即使在多次输入文本后,ArrayList 也只包含一个元素。这是代码:
public class AddQuestions implements ActionListener {
public ArrayList<String> questions;
JLabel questionLabel = new JLabel();
JTextField question = new JTextField();
JButton addButton = new JButton();
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton){
while(addButton == e.getSource()){
String value = question.getText();
questions = new ArrayList<>();
questions.add(value);
System.out.println(value);
question.setText("");
break;
}
}
System.out.println(questions);
System.out.println(questions.size());
}
}
【问题讨论】:
-
您总是在 actionPerformed 方法中使用
questions = new ArrayList<>();创建一个新的 ArrayList。您需要初始化列表一次,并且仅在单击按钮时添加,而不总是创建一个新列表。 -
不仅如此,我还没有看到
ActionListener被添加到任何地方。你可能想看看How to Write an Action Listener。
标签: java string swing arraylist