How to getText() like input[i][j].getText(); (for

2019-06-27 13:29发布

问题:

I want to get the text in int form from 81 text fields arranged in a 9 X 9grid but don't want to do it individually. I tried to put it in a loop but the problem is that the text field name has to be shown in a[i][j] form.

for (i = 0; i < 9; i++) {
    for (j = 0; j < 9; j++) {
        a[i][j] = *i want the name of text field like "a" + i + j*.getText(); 
    }
}

The text fields are name like:

a00, a01, a02, a03, a04 ... a88.

回答1:

You can't do that with java (actually there are ways of doing that, but they are complicated, error prone and most certainly not what you want. If you still want to know, look up reflection).

The solution to your problem is to make the 81 text boxes an array of text boxes

JTextField[][] input = new JTextField[9][9];
for(i=0;i<9;i++) {
    for(j=0;j<9;j++) {
        input[i][j] = new JTextField(); 
    }
}

Now you can adress each by

input[x][y]

with x and y being integers between 0 and 8 inclusive.

Especially you can do

input[x][y].getText()

To get the value from a single input field.



回答2:

You cannot reference a String to a variable like

"a" + i + j.getText();

You need to change your textfields's to something like which Jens specified.

If you don't want to change all your textfields, you need to add references for them which is not at all recommended.

JTextField [][]fields = new JTextField[9][9];
fields[0][0] = a00;
fields[0][1] = a01;
fields[0][2] = a02;
...


回答3:

You have 2 options:

A) Store your text fields in a JTextField[][] array.

B) Use reflection

Since A is already explained in other answers, I'll only focus on B.

Reflection in Java can be used to transform name of some field to the field itself, sort of.

JTextField getField(int row, int col) {
    int index = 9 * col + row; // for row-major tables
    // int index = 9*row + col; // for col-major tables

    String name = String.format("a%02d", index);
    System.out.println("Name: " + name); //For debugging purposes

    try {
        Field field = Test.class.getDeclaredField(name);

        return (JTextField) field.get(this);

    } catch (NoSuchFieldException | SecurityException
            | IllegalArgumentException | IllegalAccessException e) {
        e.printStackTrace();
        return null;
    }
}

You will need to put this code to the same class that have a00, a01, a02, ... fields declared. Also this will only get the JTextField that is stored in your field, so you can't use this to set the fields. Sililar set method could be used for that.

However, using reflection in Java is generally considered a bad practice. Here, solution A can and should be used, but if you are lazy and you don't want to rewrite your code, you can use this.