Solved

Using TableModel

Posted on 2004-04-21
37
1,501 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
Comment Utility
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
Comment Utility
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
Comment Utility
You can sort a DefaultTableModel just as well
0
 

Author Comment

by:Kennywen
Comment Utility
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
Comment Utility
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
Comment Utility
Yes, it can add any datatype. This will be easier

row.add(Boolean.FALSE);
0
 

Author Comment

by:Kennywen
Comment Utility
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
Comment Utility
Boolean.FALSE is exactly the same as new Boolean(false) which you already have in your code
0
 

Author Comment

by:Kennywen
Comment Utility
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
Comment Utility
or it's because of the vector?
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
No. The Vector will work exactly the same
0
 

Author Comment

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

Author Comment

by:Kennywen
Comment Utility
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
Comment Utility
> 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
Comment Utility
Can provide any example?

thanks
0
 
LVL 92

Expert Comment

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

dtm.addRow(row);
0
 

Author Comment

by:Kennywen
Comment Utility
DefaultTableModel will treat all data types the same.
0
 

Author Comment

by:Kennywen
Comment Utility
If i implement custom table model then how can i delete and edit the data in the table?
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 92

Expert Comment

by:objects
Comment Utility
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
Comment Utility
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
Comment Utility
can i put a check box inside the columnNames ?

thanks
0
 
LVL 37

Expert Comment

by:zzynx
Comment Utility
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
Comment Utility
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
Comment Utility
>> 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
Comment Utility
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
Comment Utility
> 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
Comment Utility
>> 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
Comment Utility
then also call scrollRectToVisible()
0
 
LVL 37

Expert Comment

by:zzynx
Comment Utility
>> 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
Comment Utility
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
Comment Utility
>>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
Comment Utility
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
Comment Utility
>>Which is pretty much exactly the same as has already been posted ???

Where and by whom?
0
 

Author Comment

by:Kennywen
Comment Utility
thanks to all
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
0
 
LVL 37

Expert Comment

by:zzynx
Comment Utility
Thank you
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
8-)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
strCount chalenge 3 50
strDist challenge 35 84
Core Java. What output will be and why ? 6 57
Image decoding from Camera 3 42
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

763 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

14 Experts available now in Live!

Get 1:1 Help Now