问题描述
我的程序首先提示用户他们想要多少文本字段
My program starts by prompting the user how many text fields they would like to have
public class textEvent1 implements ActionListener { //action listener for "how many masses?"
public void actionPerformed (ActionEvent e) {
n = (int)(Double.parseDouble(massNumField.getText()));
接下来我创建一个 for 循环来创建标签和文本字段(我已经为其创建了列表,因为我不知道会有多少).有几个列表,但我只举一个例子.
next I create a for loop to create labels and textfields (which I have created lists for because I dont know how many there will be). There are a couple of lists but I will give an example of just one.
ArrayList masses = new ArrayList();
for(int i=1; i<=n; i++) { //adds text event 2 text to the screen
massLabel = new JLabel("How much mass does Mass " +i+ " have? ");
massField = new JTextField(5);
masses.add(massField);
现在,当我尝试将质量列表的一个元素分配给像这样的变量时,我的问题出现了.
Now my problem appears to come when I try to assign an element of the masses list to a variable like so.
for(int i=1; i<=n; i++) {
mass = Double.parseDouble(((JTextComponent) masses.get(i)).getText());
我尝试了几件事...mass = mass.get(i).....mass = mass.get(i).getText()) 等等.我要么不断收到诸如 Null 指针异常之类的错误,要么说我无法 parseDouble an Object.
I have tried a couple of things...mass = masses.get(i).....mass = masses.get(i).getText()) and so on and so on. I either keep getting errors such as Null pointer exceptions or things saying I cant parseDouble an Object.
这个例子出现的错误如下
There errors that arrise for this example are as below
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3 >= 3
at java.util.Vector.elementAt(Unknown Source)
at acmx.export.java.util.ArrayList.get(ArrayList.java:54)
at Orbit$textEvent2.actionPerformed(Orbit.java:151)
第 151 行是
mass = Double.parseDouble(((JTextComponent) masses.get(i)).getText());
推荐答案
在创建 JTextFields
时,您需要:
When creating the JTextFields
, you do:
for(int i=1; i<=n; i++) {
...
请注意,List
索引从 0 开始,因此当您使用类似的循环检索项目时,使用 i
作为索引,您正在尝试访问超过最后一项.将阅读循环索引更改为:
Note that List
indices start at 0, so when you retrieve the items with a similar loop, using i
as the index, you are trying to access one past the last item. Change the reading loop indices to:
for (int i = 0; i < n; i++) {
...
或者您可以使用增强 for 循环,除非您需要使用古老的 Java 版本:
Or you could use an enhance for loop, unless you need to use an ancient java version:
for (Object massField : masses) {
mass = Double.parseDouble(((JTextComponent) massField).getText());
...
(那么你也应该真正使用泛型,如果 Java 版本支持它们).
(Then you should really use generics too, if the java version supports them).
这篇关于读取 ArrayList JTextFields的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!