-1

I want to add text fields a01, a02, ... to the array a. I want to display the value of val so that I would know if the text is being taken from text fields. This code does not show any errors, but, well, it doesn't give me output as well.

int i, j;

JTextField[][] a = new JTextField[9][9];

int[][] val = new int[9][9];

for (i = 0; i < 9; i++)
{
    for (j = 0; j < 9; j++)
    {
        val[i][j] = Integer.parseInt(a[i][j].getText());
        System.out.println(val[i][j]);
    }
}

It is from my old question here.

Community
  • 1
  • 1
GtlsGamr
  • 71
  • 7

2 Answers2

5

You did not give them value

int i,j; // counter
JTextField[][] a = new JTextField[9][9];
for(i=0;i<9;i++)
{
    for(j=0;j<9;j++)
    {
        JTextField tf = new JTextField();
        tf.setText("a"+i+j);
        a[i][j] = tf;
    }
}

In your version the call to a[i][j].getText() should throw a NullPointerException. This should either kill your application, end up on the console or you have somewhere something like

try { // more code here } catch (Exception ex){}

which will silently swallow the exception and is veeeeery bad practice.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Mingo.Link
  • 168
  • 5
  • Indeed, the OP only created an array of JTextFields without initializing it. Still, I find it surprising that he didn't get a NullPointerException when attempting to access the uninitialized text fields. – Hulk Aug 25 '15 at 04:53
  • That means he try catch-ed or init them but did not paste here – Mingo.Link Aug 25 '15 at 07:07
0

The code you have shown us does generate an error - it throws a NullPointerException when you try to access the text of the text fields via a[i][j].getText().

You didn't initialize the JTextFields in your array a.

ideone example

Hulk
  • 6,399
  • 1
  • 30
  • 52