Having a problem with getting my array into a TextArea, I originally wanted to use a JTable but found the Table Model and what to do too difficult for what I want so my question is I have my array and now I want to display it inside a TextArea, can I just create a method which will grab the array and insert it straight into a TextArea? I have displayed arrays before easily without Swing so I know how the actual "display" works but just cant get my head around this part of displaying it through the GUI.

Here is where I create my array (from textfields where the user enters)

public void readtext(){
        Adult MyArray[] = new Adult[ 5 ];
        Adult memAd = new Adult (0,"","","","","");
        int counter = 0;
		
            
        memAd.setMemName(NameTextField.getText());
        memAd.setJoinDate(DateTextField.getText());
        memAd.setMobNum(MobNumTextField.getText());
        memAd.setHomePhNum(HomeNumTextField.getText());

        counter = counter + 1;
		MyArray[counter] = memAd;
 
    }

Any advice would be great . Thanks

Recommended Answers

All 15 Replies

JTable really is the right way to do this, so it's worth the one-time effort to learn about them!
Here's a quick sample of what you need to create a suitable table model (I haven't compiled this, so expect the odd typo, but it should be good enough to get you going right).
It has a constructor to which you pass your Adults array, as in new MyTableModel(MyArray); and the rest of the methods just implement the mandatory interface required for a TableModel

class MyTableModel extends AbstractTableModel {

    private String[] columnNames = {"Name", "Date ...

    private Adult[] data;

    public myDataModel(Adult[] a) { // pass in data array to constructor
	data = a;
    }


    public int getColumnCount() {
        return columnNames.length;
    }

    public int getRowCount() {
        return data.length;
    }

    public String getColumnName(int col) {
        return columnNames[col];
    }

    public Object getValueAt(int row, int col) {
        Adult a = data[row];
        switch (col) {
           case 0: return a.getName();
           case 1: return a.getDate();
           ...

        }
    }

    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }

}
commented: Very helpful individual, patient and knowledgeable +1

Ok, thanks for the help so far.
Here is my TableModel. I am slightly confused as to how I get the array that I create and initialize in my"AddMember" class and call it in my TableModel, I have named it the exact same way put does this recognize my array from a different class?

import javax.swing.table.*;

class MyTableModel extends AbstractTableModel{

    private String[] columnNames = {"Name", "Date","Mobile Number","Home Number"};

    private Adult[] data;

    public void myDataModel(Adult[] memAd ) { // pass in data array to constructor
	data = memAd;
    }

    public int getColumnCount() {
        return columnNames.length;
    }

    public int getRowCount() {
        return data.length;
    }

    public String getColumnName(int col) {
        return columnNames[col];
    }

    public Object getValueAt(int row, int col) {
        Adult memAd = data[row];
        switch (col) {
           case 0: return memAd.getMemName();
           case 1: return memAd.getJoinDate();
           case 2: return memAd.getMobNum();
           case 3: return memAd.getMemStatus();
           case 4: return memAd.getHomePhNum();
        }
		return memAd;
    }

    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }

}

Also, here is my Table which is also in my AddMember class my question here is how do I call in my model? I tried replacing "DefaultTableModel" with my newly created model but I was getting errors. I am pretty sure I ditch all the nulls and the titles as this is all in my TableModel but not sure how to pass it in here.

jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        )

Thanks...

That is not a consructor:

public void myDataModel(Adult[] memAd ) { // pass in data array to constructor
	data = memAd;
    }

This is a constructor:

public MyTableModel(Adult[] memAd ) { // pass in data array to constructor
	data = memAd;
    }

I see that at the method: getValueAt you 5 options(col) 0-4 but in the array columnNames you have 4 elements.

Also I am not familiar with Jtables and Models, but since the call you have created IS a AbstractTableModel, maybe you can try this:

Adult [] adults = .......
//put values in the above array
 jTable1.setModel( new  MyTableModel(adults))

Check these links:
http://java.sun.com/javase/6/docs/api/javax/swing/table/AbstractTableModel.html

http://java.sun.com/javase/6/docs/api/javax/swing/table/TableModel.html

Hi, thanks for the help.

That is not a consructor:

When void is not there, I get errors. should it be MyTableModel instead of MyDataModel as there are no errors when I use MyTableModel. I am just not sure it is picking up my array from my AddMember class.

I see that at the method: getValueAt you 5 options(col) 0-4 but in the array columnNames you have 4 elements.

Yes, this is because MemNum is a static variable (auto increment) , thinking about it I don't want the user to enter it but I do want it in the table so I will sort that out.

Adult [] adults = .......
//put values in the above array
 jTable1.setModel( new  MyTableModel(adults))

I tried the above code like so:

jTable1.setModel( new MyTableModel(memAd));

but "memAd cannot be resolved"

The constructor must have the name of the class:

class MyTableModel {
  public MyTableModel() {

  }
}

Yes, this is because MemNum is a static variable (auto increment) , thinking about it I don't want the user to enter it but I do want it in the table so I will sort that out.

Even if the above is true, I believe that you still need to have the same number of columns. Since the methods getColumnCount, getColumnName will probably generate 4 columns, the values put in the cells will not be correct. Of course you could try this:

private String[] columnNames = {"Name", "Date","Mobile Number","Home Number"};

public Object getValueAt(int row, int col) {
        Adult memAd = data[row];
        switch (col) {
           case 0: return memAd.getMemName();
           case 1: return memAd.getJoinDate();
           case 2: return memAd.getMobNum();
           case 3: return memAd.getHomePhNum();

           case 4: return memAd.getMemStatus();
        }
		return memAd;
    }

but "memAd cannot be resolved"

That has nothing to do with the JTable part. You have to declare the array somewhere where it can be seen, when you try to use it

Ok, everything is sorted apart from the last issue, I have declared the array in the same class where my table is, it is declared within the function which reads the text from the textfieilds and inserts it into the array. Here is my array code:

public void readtext(){
        Adult MyArray[] = new Adult[ 5 ];
        Adult memAd = new Adult (0,"","","","","");
        int counter = 0;
		
        memAd.setMemName(NameTextField.getText());
        memAd.setJoinDate(DateTextField.getText());
        memAd.setMobNum(MobNumTextField.getText());
        memAd.setHomePhNum(HomeNumTextField.getText());

        counter = counter + 1;
		MyArray[counter] = memAd;

    }

Ok, everything is sorted apart from the last issue, I have declared the array in the same class where my table is, it is declared within the function which reads the text from the textfieilds and inserts it into the array. Here is my array code:

public void readtext(){
        Adult MyArray[] = new Adult[ 5 ];
        Adult memAd = new Adult (0,"","","","","");
        int counter = 0;
		
        memAd.setMemName(NameTextField.getText());
        memAd.setJoinDate(DateTextField.getText());
        memAd.setMobNum(MobNumTextField.getText());
        memAd.setHomePhNum(HomeNumTextField.getText());

        counter = counter + 1;
		MyArray[counter] = memAd;

    }

That has nothing to do with the JTable part. You have to declare the array somewhere where it can be seen, when you try to use it

Ok, everything is sorted apart from the last issue, I have declared the array in the same class where my table is, it is declared within the function which reads the text from the textfieilds and inserts it into the array. Here is my array code:

public void readtext(){
        Adult MyArray[] = new Adult[ 5 ];
        Adult memAd = new Adult (0,"","","","","");
        int counter = 0;
		
        memAd.setMemName(NameTextField.getText());
        memAd.setJoinDate(DateTextField.getText());
        memAd.setMobNum(MobNumTextField.getText());
        memAd.setHomePhNum(HomeNumTextField.getText());

        counter = counter + 1;
		MyArray[counter] = memAd;

    }

You seem to be getting into problems with using names in the wrong places. To keep it simple, each variable belongs to the class in which it's declared, and won't be accessible from any other class just using its name. The right way to do this is to pass the data from the first class into the next class by passing it as a parameter. So in your example, you are doing the right thing by pqssing your data into the model by making it a parameter on the constructor. Loks like your latest problem is that the class where you create the JTable doesn't have access to the data (memAd) in the first place. You should do the same thing, and pass the data to that class via a parameter in its constructor, or create the model in a class where you DO have access to memAd and pass the model into the class where the JT

Ok, I think you are right I do get confused when it comes to all this passing parameters arrays etc. As my array is only declared and initialized in the same class as my table I don't understand why it cant pick it up.

Can you tell me what my actual table code should look like because at the moment all I have for it is

jTable1.setModel(new MyTableModel(memAd);

Is this correct ? Eclipse gives an error just for the "memAd"

Thanks for the help...

The parameter for the MyTableModel constructor needs to be the array of Adults that you populated earlier. In your last code fragment that was called MyArray I think. memAd is justa simgle Adult, not the aray of Adults.
As for the JTable, you also need to do all the usual graphical obect stuff - add it to a form, set its position etcetc.

The table model is a bit much to digest for someone who is new to Java. If you are just trying to print the array contents into a text area, you can do something along the lines of this

String[][] stuff = {
    {"a","b","c"},
    {"x","y","z"},
    {"Bob","Mary","Steve"}
};
StringBuilder output = new StringBuilder();
for (int row=0; row<stuff.length; row++){
    for (int col=0; col<stuff[row].length; col++){
        output.append(stuff[row][col]);
        output.append("\t");
    }
    output.append("\n");
}
jTextArea1.setText(output.toString());

You just need to put together a string representation of each Adult object in your array and append those together into a single larger string that you can put in the text area.

Thanks for being so patient guys, just cant seem to figure this out I think I am very close though. I will post my code so far incase I am messing up with names in the wrong place etc.. Please have a look if you can

Here is my table code, there is a problem here with "memAd" but I have tried changing it to other possibles with no luck

jTable1.setModel(new MyTableModel(memAd));
jScrollPane1.setViewportView(jTable1);

Here is my array code, there are no issues with this as far as I know, although is it ok to declare and initialise it inside the same function where I insert the text from the textfields?

public void readtext(){
        Adult MyArray[] = new Adult[ 5 ];
        Adult memAd = new Adult (0,"","","","","");
        int counter = 0;
		
        memAd.setMemName(NameTextField.getText());
        memAd.setJoinDate(DateTextField.getText());
        memAd.setMobNum(MobNumTextField.getText());
        memAd.setHomePhNum(HomeNumTextField.getText());

        counter = counter + 1;
		MyArray[counter] = memAd;
    }

And here is my TableModel, should I declare in here how many columns and rows I want in or will it do it automatically depending on items it views from the array?

import javax.swing.table.*;

class MyTableModel extends AbstractTableModel{

    private String[] columnNames = {"Mem Number", "Name", "Date", "Mobile Number", "Home Number"};

    private Adult[] data;

    public MyTableModel(Adult[] memAd ) { // pass in data array to constructor
	data = memAd;
    }

    public int getColumnCount() {
        return columnNames.length;
    }

    public int getRowCount() {
        return data.length;
    }

    public String getColumnName(int col) {
        return columnNames[col];
    }

    public Object getValueAt(int row, int col) {
        Adult memAd = data[row];
        switch (col) {
           case 0: return memAd.getMemNum();
           case 1: return memAd.getMemName();
           case 2: return memAd.getJoinDate();
           case 3: return memAd.getMobNum();
           case 4: return memAd.getHomePhNum();
        }
        return memAd;
    }

    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }

}

Thanks again

As JamesCherrill mentioned above, don't pass 'memAd' to your table model constuctor, pass the Adult[] array.

public void readtext(){
        Adult MyArray[] = new Adult[ 5 ];
        Adult memAd = new Adult (0,"","","","","");
        int counter = 0;
		
        memAd.setMemName(NameTextField.getText());
        memAd.setJoinDate(DateTextField.getText());
        memAd.setMobNum(MobNumTextField.getText());
        memAd.setHomePhNum(HomeNumTextField.getText());

        counter = counter + 1;
		MyArray[counter] = memAd;
    }

You define the array inside the method but it can't be viewed from outside. It is out of scope. The MyArray array cannot be used outside that method. You need to define it outside the method as a class attribute, and use it to the constructor of your table model

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.