I'm attempting to create a large array of JTextField objects, and for some reason my code won't compile. I've played around with it for too long now, and I can't find any good reason for the compiler to be mad; here is my code with only a length 2 array:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class SUDOKU_temp extends JApplet
{
//declare fields
public JTextField[] fields = new JTextField[2];
fields[0] = new JTextField();
fields[1] = new JTextField();
//other stuff happens down here that the compiler is ok with
}
If I only run the code with a length 1 array I get the exact same errors, which are:
linux63:~demo$ ./compile
SUDOKU_temp.java:11: ']' expected
fields[0] = new JTextField();
^
SUDOKU_temp.java:11: ';' expected
fields[0] = new JTextField();
^
SUDOKU_temp.java:11: illegal start of type
fields[0] = new JTextField();
^
SUDOKU_temp.java:11: <identifier> expected
fields[0] = new JTextField();
^
SUDOKU_temp.java:11: ';' expected
fields[0] = new JTextField();
^
SUDOKU_temp.java:11: illegal start of type
fields[0] = new JTextField();
^
SUDOKU_temp.java:11: <identifier> expected
fields[0] = new JTextField();
^
I feel like this is a problem with the compiler, and not with the code, and any help about how to debug this will be greatly appreciated. Thanks in advance!!
You can't run code outside a method (unless it is a declaration). You need to either initialize them in some method or with an array literal.
Array literal:
public JTextField[] fields ={ new JTextField(),new JTextField()};
Within a method:
public JTextField[] fields=new JTextField[2];
public void method(){
fields[0]=new JTextField();
fields[1]=new JTextField();
}