0

Ok basically what I am doing is i have a jtable in which users can enter their information into the table, I then want to be able to save it into a text file. The problem I am running into however is along the lines of this.

private static String dataValues[][];  

I want to be able to declare dataValues like this so I can accesses it in every method so I can add rows to my jtable like this:

dataValues = {{number, owner, txtDate"}};
tableModel.addRow(dataValues);

however I get an error on the dataValues saying that "Array constants can only be used in initializers." And i dont really understand what that means.

if I declare the variable like this in the actual method it works.

String[][] dataValues = {{number, owner, txtDate}};

But I need to be able to access it anywhere in the program so declaring it like that will not help me.

Thanks for the help in advance.

kleopatra
  • 51,061
  • 28
  • 99
  • 211

4 Answers4

2

The JTable represents the data internally with a TableModel. What the JTable does in the constructor is convert the initial array into the TableModel. What you need to do is think in terms of TableModels as described in the following link: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data

Stephane Grenier
  • 15,527
  • 38
  • 117
  • 192
1

You can always initialize array variables like so:

static String[] row;

and later:

row = new String[]{"foo", "bar", "baz"};
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
1

"Array constants can only be used in initializers." - is a java syntax error. You can not use statement like :

 int[] a = new int [3];
 a = {1,2,3};

I think with "a = {...}" it is not clear to the "javac" compiler what the type of "a" is. Especially when dealing with array of objects such as Strings.

So use of constants allowed are

 int[] a = {1,2,3};

Or possibly

a = new int [] {1,2,3};

Above should the only way if you really want to do what you are trying to do. Essentially, this is how your code would look like:

dataValues = new String[][] {{"number", "owner", "txtDate"}};

That for the Java syntax error part. For JTable stuff, please follow @Stphane G's answer

ring bearer
  • 20,383
  • 7
  • 59
  • 72
0

Have a look at this answer i had given for a question on using a generic table model. You will find using a class with the fields representing the columns of the table a very easy implementation to work with

Is there a generic TableModel we can use in JTables?

Community
  • 1
  • 1
sethu
  • 8,181
  • 7
  • 39
  • 65