Solved

Using TableModel

Posted on 2004-04-21
37
1,502 Views
Last Modified: 2013-11-23
Sample code as below:
TableSorter sorter = new TableSorter(new MyTableModel1()); // TableSorter is a class to enable the table sorting
JTable table = new JTable(sorter);

class MyTableModel1 extends AbstractTableModel {
       private String[] columnNames = {"","Date & Time",
                                        "Originator",
                                        "Sent To"};
        private Object[][] data = {
            {new Boolean(false),"2004-04-03 10:01:05", "+60126343439",
             "+60126343439"},
            {new Boolean(false),"2004-04-08 10:01:05", "+60126343439",
             "+60126343439"},
            {new Boolean(false),"2004-04-13 10:01:05", "+60126343439",
             "+60126343439"}
        };

      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) {
            return data[row][col];
        }

        /*
         * JTable uses this method to determine the default renderer/
         * editor for each cell.  If we didn't implement this method,
         * then the last column would contain text ("true"/"false"),
         * rather than a check box.
         */
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        /*
         * Don't need to implement this method unless your table's
         * editable.
         */
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col != 0) {
                return false;
            } else {
                return true;
            }
        }

        /*
         * Don't need to implement this method unless your table's
         * data can change.
         */
        public void setValueAt(Object value, int row, int col) {
            if (DEBUG) {
                System.out.println("Setting value at " + row + "," + col
                                   + " to " + value
                                   + " (an instance of "
                                   + value.getClass() + ")");
            }

            data[row][col] = value;
            fireTableCellUpdated(row, col);

            if (DEBUG) {
                System.out.println("New value of data:");
                printDebugData();
            }
        }

    }

but now i facing a problem that is how can i assign the table value from the text file?

try
            {
                  String text = null;
                  int counter =0;
                  BufferedReader buf = new BufferedReader(new FileReader("phone.csv"));
            while ( (text = buf.readLine()) != null) {
               if (text.trim().length()>0)
                        {
                           counter++; // count non-empty lines
                        }
            }      
                  //buf.flush();
                  buf.close();
                  
                  Object[][] dataPhone = new Object[counter][3];
                  //System.out.println(data.length);
            BufferedReader buf1 = new BufferedReader(new FileReader("phone.csv"));
            counter=0;
            while ( (text = buf1.readLine()) != null) {
               text=text.trim();
               if (text.length()==0)  continue; // empty line
               String[] split = text.split(",");
               for (int j=0;j<split.length;j++) // for each field:
               {
                           dataPhone[counter][j] = split[j];

               }
                counter++;
            }

thank in advance
0
Comment
Question by:Kennywen
  • 15
  • 8
  • 8
  • +1
37 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 10884707
As i mentioned in your last question, you don't need to read the file twice to get the line count, you can just create the table model using Vectors and read the file once
0
 

Author Comment

by:Kennywen
ID: 10884717
But in ur previous example it's using the DefaultTableModel but now i want to enable the table sorting .
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10884740
You can sort a DefaultTableModel just as well
0
 

Author Comment

by:Kennywen
ID: 10884763
an error:
BoxAlignmentDemo.java:512: cannot resolve symbol
symbol  : constructor DefaultTableModel (java.util.Vector,java.lang.String[])
location: class javax.swing.table.DefaultTableModel
                DefaultTableModel dtm = new DefaultTableModel(data, columnNames);

String[] columnNames = {"","Name","Mobile Number"};
0
 

Author Comment

by:Kennywen
ID: 10884872
CEHJ i'm using your example but it cannot add the boolean data type:

Vector data = new Vector();
while ( (text = buf1.readLine()) != null) {
      text=text.trim();
      String[] values = text.split(",");
      Vector row = new Vector();
      for(int i = 0;i < values.length+1;i++) {
      if (i==0)
      {
            row.add(new Boolean(false));
      }
      else
      {
            row.add(values[i-1].trim()); // adjust if different data types required
      }
}
data.add(row);

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10884888
Yes, it can add any datatype. This will be easier

row.add(Boolean.FALSE);
0
 

Author Comment

by:Kennywen
ID: 10884901
The table will only display the word "false" instead of display the check box.
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 25 total points
ID: 10884928
Boolean.FALSE is exactly the same as new Boolean(false) which you already have in your code
0
 

Author Comment

by:Kennywen
ID: 10884946
private Object[][] data = {
            {new Boolean(false),"2004-04-03 10:01:05", "+60126343439",
             "+60126343439"},
            {new Boolean(false),"2004-04-08 10:01:05", "+60126343439",
             "+60126343439"},
            {new Boolean(false),"2004-04-13 10:01:05", "+60126343439",
             "+60126343439"}
        };

the above code's new Boolean(false) will display a check box inside the table.
0
 

Author Comment

by:Kennywen
ID: 10884950
or it's because of the vector?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10884976
No. The Vector will work exactly the same
0
 

Author Comment

by:Kennywen
ID: 10885021
Is't possible to create a check box inside the table by using new Boolean(false)?
0
 

Author Comment

by:Kennywen
ID: 10885195
I just find out that i must implement my own table model in order to make the boolean datatype to display as check box in table. but i don't know how to put the data to the table from a csv file.

See the sample code at above.

thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 10885244
> Is't possible to create a check box inside the table by using new Boolean(false)?

sure is.

> but i don't know how to put the data to the table from a csv file.

Depends on the table model you are using.
The model u are using above doesn't provide a means to add data.
0
 

Author Comment

by:Kennywen
ID: 10885260
Can provide any example?

thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 10885294
If you use DefaultTableModel then it provides you with methos to add rows of data.

dtm.addRow(row);
0
 

Author Comment

by:Kennywen
ID: 10885309
DefaultTableModel will treat all data types the same.
0
 

Author Comment

by:Kennywen
ID: 10885319
If i implement custom table model then how can i delete and edit the data in the table?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 92

Expert Comment

by:objects
ID: 10885324
Just subclass DTM and override anything you need to:

public class MyTableModel extends DefaultTableModel
{
   ...
}
0
 
LVL 37

Accepted Solution

by:
zzynx earned 75 total points
ID: 10886014
class MyClass {
   private Boolean myBool;
   private Date myDate;
   private String originator;
   private String sentTo;

   public MyClass() {
   }
   public void setMyBool(boolean b) {
      myBool = new Boolean(b);
   }
   public void setMyDate(Date d) {
      myDate = d;
   }
   public void setOriginator(String o) {
      originator = o;
   }
   public void setSentTo(String s) {
      sentTo = s;
   }
   public Boolean getMyBool() { return myBool; }
   public Date getMyDate() { return myDate; }
   public String getOriginator() { return originator; }
   public String getSentTo() { return sentTo; }
}

class MyTableModel1 extends DefaultTableModel {

       private String[] columnNames = {"","Date & Time", "Originator", "Sent To"};
       private List data = new ArrayList(); // list of MyClass objects

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

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

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

       public Object getValueAt(int row, int col) {
        MyClass mine = (MyClass) data.get(row);
          if (col==0) return mine.getMyBool();
          else if (col==1) return mine.getMyDate();
          else if (col==2) return mine.getOriginator();
          else if (col==3) return mine.getSentTo();
       }

       /*
        * JTable uses this method to determine the default renderer/
        * editor for each cell.  If we didn't implement this method,
        * then the last column would contain text ("true"/"false"),
        * rather than a check box.
        */
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        /*
         * Don't need to implement this method unless your table's
         * editable.
         */
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col != 0) {
                return false;
            } else {
                return true;
            }
        }

        /*
         * Don't need to implement this method unless your table's
         * data can change.
         */
        public void setValueAt(Object value, int row, int col) {
          MyClass mine = (MyClass) data.get(row);
            if (col==0) mine.setMyBool((Boolean)value);
            // Commented to be in accordance with isCellEditable:
            //else if (col==1) mine.setMyDate((Date)value);
            //else if (col==2) mine.setOriginator((String)value);
            //else if (col==3) mine.setSentTo((String)value);
        }

        public void add(MyClass mine) {
            data.add(mine);
        }
        public void remove(int index) {
            data.remove(index);
        }
}
0
 

Author Comment

by:Kennywen
ID: 10886038
can i put a check box inside the columnNames ?

thanks
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10886136
You mean in the header?
Everything is possible.

You have to write your own
public class MyHeaderRenderer extends DefaultTableCellRenderer {
  ...
}

which adds a checkbox (and listen to the checking of them, ...)

and then

        JTableHeader header = table.getTableHeader();
        header.setDefaultRenderer(new MyHeaderRenderer());
0
 
LVL 92

Expert Comment

by:objects
ID: 10886207
If you want to use checkboxes then the following model should do it:

public class MyTableModel extends DefaultTableModel
{
   public Class getColumnClass(int col)
   {
      return col==0 ? Boolean.class : super.getColumnClass(col);
   }

}

When reading your CSV file use the addRow() method to add each row (with a Boolean in column 0).
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10886447
>> can i put a check box **inside the columnNames**?
objects, according to the above, I don't think he's talking about check boxes in the first column, but in the headers.

KennyWen, could you make clear what exactly you want?
0
 

Author Comment

by:Kennywen
ID: 10886497
yes, i want to put the check in the table header.

another question can i set focus to the specify row? E.g. currently the table is focus on row number 1 so how can i change it to focus on row number 50, that mean the table will auto scroll down to the row number 50.

thanks
0
 
LVL 92

Assisted Solution

by:objects
objects earned 25 total points
ID: 10886573
> yes, i want to put the check in the table header.

then use a custom header renderer as zzynx suggested.
you can find a few examples of custom header renderers at:
http://www.objects.com.au/java/examples.do
(none using a checkbox but the principle is the same).

> another question can i set focus to the specify row?

table.setRowSelectionInterval(row, row);

0
 

Author Comment

by:Kennywen
ID: 10886605
>> table.setRowSelectionInterval(row, row);

the above code will only set focus to the particular row but i want the table auto scroll down to the specify row.

thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 10886640
then also call scrollRectToVisible()
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10886641
>> another question...
Another one? ;)

>> table.setRowSelectionInterval(row, row);
That's for selecting a row

To make sure a row (or a certain cell) is visible (without selecting it):
http://www.codeguru.com/java/articles/161.shtml
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10886671
Easier:

How can I make a certain cell/row/column visible?
For cells, it can be done easily with: table.scrollRectToVisible(table.getCellRect(row, column, true));

quote from http://www.chka.de/swing/table/faq.html
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10887562
>>Is't possible to create a check box inside the table by using new Boolean(false)?

It is, but as i said, it's not necessary as this runnable example demonstrates. You need to blend in the code i gave you in your last question:

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.*;

public class JTableDemo extends JFrame {
      private JTable table;
      public final static String[] columnNames = {"", "Date & Time",
                  "Originator",
                  "Sent To"};
      public JTableDemo() {

            table = new JTable(createModel());
            JScrollPane sp = new JScrollPane(table);
            getContentPane().add(sp, BorderLayout.CENTER);
      }
      
      public TableModel createModel() {
            DefaultTableModel model =
                  new DefaultTableModel() {

                        public boolean isCellEditable(int row, int col) {
                              return col == 0;
                        }

                        public Class getColumnClass(int col) {
                              return col == 0 ? Boolean.class : String.class;
                        }
                  };

            Vector row1 = new Vector();
            row1.add(Boolean.FALSE);
            row1.add("2004-04-03 10:01:05");
            row1.add("+60126343439");
            row1.add("+60126343439");

            model.getDataVector().add(row1);

            model.setColumnIdentifiers(columnNames);
            return model;
      }
      
      public static void main(String[] args) {
            JTableDemo frame = new JTableDemo();
            frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
      }
}
0
 
LVL 92

Expert Comment

by:objects
ID: 10887580
Which is pretty much exactly the same as has already been posted ???
Please read the guidelines for posting comments, though I really shouldn't need to keep reminding you.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10887596
>>Which is pretty much exactly the same as has already been posted ???

Where and by whom?
0
 

Author Comment

by:Kennywen
ID: 10895499
thanks to all
0
 
LVL 92

Expert Comment

by:objects
ID: 10895507
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10896806
Thank you
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10897789
8-)
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now