【问题标题】:How do I add JTextField text to a String[] array如何将 JTextField 文本添加到 String[] 数组
【发布时间】:2019-09-17 16:20:16
【问题描述】:

单击JButton 后,我需要将输入JTextField 的文本添加到String[] storing。我不允许使用ArrayList,所以请不要推荐。例如,我会有一个JTextField,我会写一个语句,例如,“代码测试”,然后点击一个JButton,然后点击JButton,“代码测试”应该添加到一个@987654328 @。我需要继续为每个新文本添加到String[] storing,然后单击JButton

    if(event.getSource() == buttonj) {
storing[jtextf.getText()];

}

【问题讨论】:

  • 你能用其他的Collection吗?

标签: java arrays string swing


【解决方案1】:

在这种情况下,您应该做的是在按钮的事件侦听器之外有一些整数变量,但仍在同一个类中,表示当前storing 中的字符串数。然后在添加新元素时使用此计数对数组进行索引,并在每次添加新字符串时递增计数,

private static int count = 0;

if(event.getSource() == buttonj) {
    if(count < storing.length) {
        storing[count] = jtextf.getText();
        count++;
    }
}

就像用户 Kevin Anderson 提到的那样,当你的数组变满时要小心,也就是 count == storing.length 时。此时,您可以不添加元素,因为数组被认为是“满的”,或者调整数组的大小以适应新元素。不过,我会把这部分留给你。

【讨论】:

  • 不要忘记考虑当storing 已满时(即count == storing.length)会发生什么。
  • @KevinAnderson 好点,刚刚编辑了我的答案以包含它。
猜你喜欢
  • 1970-01-01
  • 2023-03-10
  • 2020-02-26
  • 1970-01-01
  • 2018-04-18
  • 1970-01-01
  • 2016-10-02
  • 2013-11-28
  • 2022-12-05
相关资源
最近更新 更多