首页 > 解决方案 > 每次单击按钮时如何将值写入不同的文本字段?

问题描述

我无法克服这个问题,需要您的帮助

图片

每次我单击停止按钮时,都会在上面的字段中生成一个随机数。我想要做的是将每个数字保存在左侧字段中。文本字段的名称为 textField_0、textField_1、textField_2 等。

izvucen = rnd.nextInt(31) + 1;
randomField.setText(Integer.toString(izvucen)); 
textField_i.setText(Integer.toString(izvucen)); // critical line, need to replace "i" with something
i++;

标签: javaswingtextfield

解决方案


您可以在创建所有文本字段时将它们放在一个列表中,并通过索引访问它们

txtFields.get(i).setText(...)

或将所有字段放入地图 ( Map<Integer, TextField>) 并通过以下方式访问特定字段get()

mapOfTextFields.get(i).setText()

推荐阅读