Using TableModel

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
KennywenAsked:
Who is Participating?
 
zzynxSoftware engineerCommented:
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
 
CEHJCommented:
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
 
KennywenAuthor Commented:
But in ur previous example it's using the DefaultTableModel but now i want to enable the table sorting .
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
CEHJCommented:
You can sort a DefaultTableModel just as well
0
 
KennywenAuthor Commented:
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
 
KennywenAuthor Commented:
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
 
CEHJCommented:
Yes, it can add any datatype. This will be easier

row.add(Boolean.FALSE);
0
 
KennywenAuthor Commented:
The table will only display the word "false" instead of display the check box.
0
 
CEHJCommented:
Boolean.FALSE is exactly the same as new Boolean(false) which you already have in your code
0
 
KennywenAuthor Commented:
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
 
KennywenAuthor Commented:
or it's because of the vector?
0
 
CEHJCommented:
No. The Vector will work exactly the same
0
 
KennywenAuthor Commented:
Is't possible to create a check box inside the table by using new Boolean(false)?
0
 
KennywenAuthor Commented:
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
 
objectsCommented:
> 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
 
KennywenAuthor Commented:
Can provide any example?

thanks
0
 
objectsCommented:
If you use DefaultTableModel then it provides you with methos to add rows of data.

dtm.addRow(row);
0
 
KennywenAuthor Commented:
DefaultTableModel will treat all data types the same.
0
 
KennywenAuthor Commented:
If i implement custom table model then how can i delete and edit the data in the table?
0
 
objectsCommented:
Just subclass DTM and override anything you need to:

public class MyTableModel extends DefaultTableModel
{
   ...
}
0
 
KennywenAuthor Commented:
can i put a check box inside the columnNames ?

thanks
0
 
zzynxSoftware engineerCommented:
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
 
objectsCommented:
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
 
zzynxSoftware engineerCommented:
>> 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
 
KennywenAuthor Commented:
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
 
objectsCommented:
> 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
 
KennywenAuthor Commented:
>> 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
 
objectsCommented:
then also call scrollRectToVisible()
0
 
zzynxSoftware engineerCommented:
>> 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
 
zzynxSoftware engineerCommented:
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
 
CEHJCommented:
>>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
 
objectsCommented:
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
 
CEHJCommented:
>>Which is pretty much exactly the same as has already been posted ???

Where and by whom?
0
 
KennywenAuthor Commented:
thanks to all
0
 
objectsCommented:
0
 
zzynxSoftware engineerCommented:
Thank you
0
 
CEHJCommented:
8-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.