Like getText () as input [i] [j] .getText (); (for solving sudoku in netbeans)

I want to get text in int form from 81 text fields located in a 9 X 9 grid, but I don't want to do it individually. I tried putting it in a loop, but the problem is that the name of the text field should be displayed in the form a[i][j] .

 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(); } } 

Text fields are called:

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

+4
source share
3 answers

You cannot do this with java (there are actually ways to do this, but they are complex, error prone and, of course, not what you want. If you still want to know, look at the reflection).

The solution to your problem is to make 81 text field an array of text fields

 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 specify

 input[x][y] 

where x and y are integers from 0 to 8 inclusive.

Especially you can do

 input[x][y].getText() 

To get a value from one input field.

+2
source

You cannot reference String to a variable of type

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

You need to change your text fields to something like what Jens pointed out.

If you do not want to change all text fields, you need to add links for them, which are not recommended.

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

You have 2 options:

A) Save the text fields in the JTextField[][] array.

B) Use reflection

Since A has already been explained in other answers, I will focus only on B

Reflection in Java can be used to convert the name of some field to the field itself, of a kind.

 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 in the same class that has the declared fields a00, a01, a02, ... It will also get a JTextField that is stored in your field, so you cannot use this to set fields. For this, the silylar kit method can be used.

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

0
source

All Articles