【问题标题】:How to add user input from text field into an array?如何将文本字段中的用户输入添加到数组中?
【发布时间】:2020-07-09 03:59:33
【问题描述】:

当我单击“添加”按钮时,我正在尝试将文本字段中的用户输入添加到数组中。显示按钮显示整个数组。我已经在程序的其他位置初始化了数组 (array = new String[10])。我将计数器初始化为 0 作为私有变量。如果用户输入的字符串超过 10 个,则不应添加输入。有什么建议吗?

    // if add button is clicked
    if (e.getSource() == btnAdd){

        /*input = textInput.getText();
        output = textOutput.getText() + input + "\n";
        textOutput.setText(output);*/

        // get user input from text field
        input = textInput.getText();  

        // clear text input field
        textInput.setText("");

        /*do {

            array[counter] = input;
            counter++;

        } while (counter < 11);

        if (counter > 10){

            picBottom = new TextPicture(new String("No Space Available"), new Font("TimesRoman", Font.ITALIC, 30), new Color(0));
            picBottom.setC(Color.RED);
        }*/

        // add user input to array if counter is within array length
        if (counter <= 10){

            array[counter] = input;
            counter++;
        }

        // display no more space available if counter is outside of array length
        else {

            picBottom = new TextPicture(new String("No Space Available"), new Font("TimesRoman", Font.ITALIC, 30), new Color(0));
            picBottom.setC(Color.RED);
        }
    }

    // if display button is clicked
    else if (e.getSource() == btnDisplay){

        // go through array & display each string
        for (int i = 0; i <= counter; i++){

            output += array[i];
            textOutput.setText(output);
        }
    }

【问题讨论】:

  • array = textfield.getText().toCharArray(); 呢?
  • 数组为String数组
  • 还有什么问题?发布的代码看起来很合理。您是否在 if 语句中添加了任何调试代码以查看代码是否已执行?
  • 当我输入超过 10 个输入时,控制台屏幕上会弹出错误。我相信当单击添加按钮时,错误出现在 if else 语句中。如果输入少于 10 个,则显示按钮在数组前后显示“null”。
  • counter 从 0 开始计数。所以你有变化:if (counter &lt;= 10)if (counter &lt; 10) 所以 counter 只能是 0, 1, ....8, 9 就像你定义的数组一样。跨度>

标签: java arrays swing jtextfield


【解决方案1】:

这里有一个最简单的例子:

JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 300, 300);

JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(300, 150));

JTextField txtField = new JTextField("");
txtField.setPreferredSize(new Dimension(200, 30));

JButton button = new JButton("Push me");
button.addActionListener((ActionEvent arg0) -> {
    if(counter < 10){
        array[counter] = txtField.getText();
        counter++;
        txtField.setText("");
        txtField.requestFocus();
    }
    else{
        System.out.println("No Space Available");
    }


    System.out.println(Arrays.toString(array));
});
panel.add(txtField);
panel.add(button);

frame.add(panel);
frame.setVisible(true);

【讨论】:

  • 感谢您的帮助,现在更有意义了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多