【问题标题】:Adding a String in an ArrayList everytime a button is clicked每次单击按钮时在 ArrayList 中添加一个字符串
【发布时间】: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&lt;&gt;(); 创建一个新的 ArrayList。您需要初始化列表一次,并且仅在单击按钮时添加,而不总是创建一个新列表。
  • 不仅如此,我还没有看到ActionListener 被添加到任何地方。你可能想看看How to Write an Action Listener

标签: java string swing arraylist


【解决方案1】:

删除while 是不必要的,因为当点击按钮时actionPerformed() 只会触发一次。

另外,actionPerformed() 内的questions = new ArrayList&lt;&gt;() 将始终将对象questions 重新初始化到新的内存位置,因此您之前添加的值会丢失。

public class AddQuestions implements ActionListener {

  public ArrayList<String> questions=new ArrayList<>();
  JLabel questionLabel = new JLabel();
  JTextField question = new JTextField();
  JButton addButton = new JButton();
  
  @Override
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == addButton){
      
      String value = question.getText();
      questions.add(value);
      System.out.println(value);
      question.setText("");
      
      
    }
    System.out.println(questions);
    System.out.println(questions.size());
    
  }
}

我建议你阅读Java Programming by Joyce Farrell 来了解更多关于java 的知识,这是一本适合初学者的好书。它有大量的编程练习让你记住java。

【讨论】:

  • while 循环使周围的 if 语句变得多余。但更糟糕的是,如果满足它的条件,它将无限循环。我不会说这是“不必要的”,而是“不想要的”或问题。
【解决方案2】:

每次点击 Button 后,都会为 ArrayList 创建新对象,因此您需要在事件之前初始化 ArrayList 的对象,即在 actionPerformed 事件方法之上。

【讨论】:

    猜你喜欢
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多