TableModel

My GUI project fetches data from SQL server (using JDBC-ODBC's ResultSet),
and returns to a table to display all data.
Everything works fine, but it doesn't set focus on the
first row (I want to default to high-light first row when this table gets data from database).
Is there any way to do that?
The code like this
if (model.getRowCount() != 0){
//I want to setfocus on the first row
//is there any constructor for tableModel here to do that?

Hi crowabysa,
If (model.getRowCount() != 0)
table.setRowSelectionInterval(0,0);}
This one highlights the first row, which is not necessarily the same as setting the focus on the first row.
I hope this will help you out.
Regards,
Tirumalarao
Developer Technical Support,
Sun Microsystems,
http://www.sun.com/developers/support.

Similar Messages

  • Hiding a column while keeping the data in the TableModel

    Hello
    I am reading data in from a database and I add the data from the resultSet to
    a vector of vectors.
    e.g my table
    user_id | user_fname | user_lname | prj_id | prj_name
    I am reading in the above information but I dont want to
    display the id fields i.e
    the user_id and
    the prj_id fields
    to the user but I need to keep them in the vector inside my tablemodel
    for futher database manipulation.
    I've looked at threads saying to set the width of the column to 0 is this the best way???
    Could someone please share with me a way to do the above.
    Thank you very much

    Figure out how to call the removeColumn method on your JTable. Calling the method only removes the column viewed (JTable), not the actual column in the (DefaultTable) Model.
    If you go for the proposed "do it so small it cant be seen" solution, you have to "lock" the colum width so users can't do it bigger manually with the mouse...

  • Deleting a row from a JTable using a custom TableModel

    Before I waste any of your time I would like to go ahead and just say that I have searched through the forum using "delete row from Jtable" as the search keywords and while I have found very closely related issues, they have not solved my problem. I have found code postings by carmickr and his arguments as to why we should use DefaultTableModel instead of having created our own custom TableModel, and while I do agree, I just am not quite confident enough in applying it to my scenario. See I am reading from a file a bunch of Contractor objects and I am stuffing it into an arraylist which I am using in the following code posting to populate my TableModel which the JTable object in the gui then uses.
    My problem is that everything works except when I delete and when I delete I understand that the index is changing because I just removed a row from the arraylist object. Suppose I have 33 rows displaying in the GUI. Now after I delete say row #23, the delete function works and dutifuly the row disappears from the table, but if I try to delete a row say...the last row, it does not work and throws me an IndexOutOfBoundsException which totally makes sense. My question is how do I go about fixing it? Do I have to do something with the setRowCount method?
    Any help is appreciated.
    Cheers,
    Surya
    * ContractorTableModel.java
    * Created on January 12, 2006, 11:59 PM
    package code.suncertify.gui;
    import java.util.ArrayList;
    import java.util.logging.Logger;
    import javax.swing.table.AbstractTableModel;
    import code.suncertify.db.Contractor;
    * @author Surya De
    * @version 1.0
    public class ContractorTableModel extends AbstractTableModel {
         * The Logger instance. All log messages from this class are routed through
         * this member. The Logger namespace is <code>sampleproject.gui</code>.
        private Logger log = Logger.getLogger("code.gui");
         * An array of <code>String</code> objects representing the table headers.
        private String [] headerNames = {"Record Number", "Contractor Name",
        "Location", "Specialties","Size", "Rate",
        "Owner"};
         * Holds all Contractor instances displayed in the main table.
        private ArrayList <Object> contractorRecords = new ArrayList<Object>(5);
         * Returns the column count of the table.
         * @return An integer indicating the number or columns in the table.
        public int getColumnCount() {
            return this.headerNames.length;
         * Returns the number of rows in the table.
         * @return An integer indicating the number of rows in the table.
        public int getRowCount() {
            return this.contractorRecords.size();
         * Gets a value from a specified index in the table.
         * @param row An integer representing the row index.
         * @param column An integer representing the column index.
         * @return The object located at the specified row and column.
        public Object getValueAt(int row, int column) {
            Object [] temp = (Object[]) this.contractorRecords.get(row);
            return temp[column];
         * Sets the cell value at a specified index.
         * @param obj The object that is placed in the table cell.
         * @param row The row index.
         * @param column The column index.
        public void setValueAt(Object obj, int row, int column) {
            Object [] temp = (Object []) this.contractorRecords.get(row);
            temp [column] = obj;
         * Returns the name of a column at a given column index.
         * @param column The specified column index.
         * @return A String containing the column name.
        public String getColumnName(int column) {
            return headerNames[column];
         * Given a row and column index, indicates if a table cell can be edited.
         * @param row Specified row index.
         * @param column Specified column index.
         * @return A boolean indicating if a cell is editable.
        public boolean isCellEditable(int row, int column) {
            return false;
         * Adds a row of Contractor data to the table.
         * @param specialty
         * @param recNo The record number of the row in question.
         * @param name The name of the contractor.
         * @param location Where the contractor is located
         * @param size Number of workers for the contractor
         * @param rate The contractor specific charge rate
         * @param owner Name of owner
        public void addContractorRecord(int recNo, String name,
                String location, String specialty,
                int size, float rate, String owner) {
            Object [] temp = {new Integer(recNo), name,
            location, specialty, new Integer(size),
            new Float(rate), owner};
            this.contractorRecords.add(temp);
            fireTableDataChanged();
         * Adds a Contractor object to the table.
         * @param contractor The Contractor object to add to the table.
        public void addContractorRecord(Contractor contractor) {
            Object [] temp = {new Integer(contractor.getRecordNumber()),
            contractor.getName(), contractor.getLocation(),
            contractor.getSpecialties(), new Integer(contractor.getSize()),
            new Float(contractor.getRate()), contractor.getCustomerID()};
            this.contractorRecords.add(temp);
            fireTableDataChanged();
         * Deletes a row of Contractor data to the table.
         * @FIXME Now that I deleted a row then I will have to reset the internal structure so that I can delete again
         * @param recNo The record number of the row in question.
        public void deleteContractorRecord(int recNo) {
            contractorRecords.remove(recNo - 1);
            fireTableRowsDeleted(recNo -1, recNo - 1);
    }

    Wow that was a very quick response. Thanks camickr. I am only trying to delete a single row. I do not know how to go about posting a test program for the code I have posted above because honestly the gui itself is 800 lines of code, and then the file reading class is quite funky in itself. I can maybe email you the entire Netbeans project including code so if you are using Netbeans 5 RC2 you can run the code and see for yourself, but that would not be considerate of me.
    See I am trying to delete any row at any time...but only one at a time not multiple rows...so if a user decides to delete row 23 and then tries to delete the last row which happens to be row 33 in my case, my setup should be smart enough to still allow to delete the row.

  • JTable and ResultSet TableModel with big resultset

    Hi, I have a question about JTable and a ResultSet TableModel.
    I have to develop a swing JTable application that gets the data from a ResultSetTableModel where the user can update the jtable data.
    The problem is the following:
    the JTable have to contain the whole data of the source database table. Currently I have defined a
    a TYPE_SCROLL_SENSITIVE & CONCUR_UPDATABLE statement.
    The problem is that when I execute the query the whole ResultSet is "downloaded" on the client side application (my jtable) and I could receive (with big resultsets) an "out of memory error"...
    I have investigate about the possibility of load (in the client side) only a small subset of the resultset but with no luck. In the maling lists I see that the only way to load the resultset incrementally is to define a forward only resultset with autocommit off, and using setFetchSize(...). But this solution doesn't solve my problem because if the user scrolls the entire table, the whole resultset will be downloaded...
    In my opinion, there is only one solution:
    - create a small JTable "cache structure" and update the structure with "remote calls" to the server ...
    in other words I have to define on the server side a "servlet environment" that queries the database, creates the resultset and gives to the jtable only the data subsets that it needs... (alternatively I could define an RMI client/server distribuited applications...)
    This is my solution, somebody can help me?
    Are there others solutions for my problem?
    Thanks in advance,
    Stefano

    The database table currently is about 80000 rows but the next year will be 200000 and so on ...
    I know that excel has this limit but my JTable have to display more data than a simple excel work sheet.
    I explain in more detail my solution:
    whith a distribuited TableModel the whole tablemodel data are on the server side and not on the client (jtable).
    The local JTable TableModel gets the values from a local (limited, 1000rows for example) structure, and when the user scroll up and down the jtable the TableModel updates this structure...
    For example: initially the local JTable structure contains the rows from 0 to 1000;
    the user scroll down, when the cell 800 (for example) have to be displayed the method:
    getValueAt(800,...)
    is called.
    This method will update the table structure. Now, for example, the table structure will contain data for example from row 500 to row 1500 (the data from 0 to 499 are deleted)
    In this way the local table model dimension will be indipendent from the real database table dimension ...
    I hope that my solution is more clear now...
    under these conditions the only solutions that can work have to implement a local tablemodel with limited dimension...
    Another solution without servlet and rmi that I have found is the following:
    update the local limited tablemodel structure quering the database server with select .... limit ... offset
    but, the select ... limit ... offset is very dangerous when the offset is high because the database server have to do a sequential scan of all previuous records ...
    with servlet (or RMI) solution instead, the entire resultset is on the server and I have only to request the data from the current resultset from row N to row N+1000 without no queries...
    Thanks

  • Why are getColumnClass/getColumnName in TableModel, not TableColumnModel?

    Shouldn't the TableColumnModel be responsible for keeping information about the table columns? Things such as column classes and names? Why are these things retrieved through TableModel only? This doesn't seem to follow OO concepts, what am I missing?
    Along those same lines, why are methods such as getColumnCount() in both TableModel and TableColumnModel? Again, this seems appropriate to TableColumnModel, but not TableModel, except maybe as a convenience. Am I misunderstanding the roles of these models?

    The TableModel holds the data for each line and for the headers. So it is naturally the place to ask for informations like "how much rows do I have" or "how much columns do I have" or "what is the name of column x".
    The ColumnModel is responsible for specifications on a column, so it naturally should be able to tell all that the TableModel can tell about it, too.
    I don't see a problem in being able to ask both. I would be annoyed if I would not be able to do so and I can see no OO principle broken.
    Rommie.

  • How make a jCheckBox editable in a table with personal TableModel?

    Hi, first of all sorry about my English, ;)
    I made my own Table Model with this simple characteristics:
    - All rows isn't editables.
    - Backgound colors changed.
    - Get a Object[][] and Strin[] in his constructor.
    - Accept booleans type and put in the cell a checkBox, checked or unchecked.
    Well, most easy to explind, here's the code.
    * elperlaTableModel.java
    * Created on 12 de febrero de 2007, 18:24
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package elperla;
    import GUI.elperla.*;
    import javax.swing.*;
    import java.sql.*;
    import java.awt.Color;
    import java.util.Vector;
    import javax.swing.JTable;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class elperlaTableModel
    extends      AbstractTableModel
    implements   ListSelectionListener
        public int nCols;
        public int nRows;
        public int editableColumn;
        public Object [] tittles;
        public Object [][] tabledata;
        public JViewport viewport;
        public JTable table;
        public elperlaTableModel(Object [][] tabledata, Object [] tittles) throws Exception{
            super();
            nCols           = tittles.length;
            nRows           = tabledata.length;
            editableColumn  = -1;
            this.tittles    = tittles;
            this.tabledata  = tabledata;
            /*Inicialitzaci� de objectes GUI*/
            ListSelectionModel  listSM      = null;
            viewport                        = new JViewport();
            TableSorter sorter              = new TableSorter(this);
            table                           = new JTable(sorter);
            sorter.setTableHeader(table.getTableHeader());
            listSM                          = table.getSelectionModel();
            viewport.add(table);
            /*Canviem l'aparen�a de la taula*/
            table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
            Color colorBack = new Color(255, 255, 255);
            Color colorSelBack = new Color(255,153,51);
            table.setBackground(colorBack);
            table.setSelectionBackground(colorSelBack);
            listSM.addListSelectionListener(this);
        public int getRowCount(){
            return nRows;
        public int getColumnCount(){
            return nCols;
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        public String getColumnName(int column){
            String name = tittles[column].toString();
            if (name == null) return null;
            else return name.toString();
        public boolean isCellEditable(int row, int col){
            if (col == this.editableColumn)
                return true;
            else
                return false;
        public void setEditableColumn(int c){
            this.editableColumn = c;
        public void setTittles(String [] tittles){
            this.tittles = tittles;
        public void setData(Object [][] tabledata){
            this.tabledata = tabledata;
        public void setViewport(JViewport viewport){
            this.viewport = viewport;
        public Object getValueAt(int row, int column){
            Object o = tabledata[row][column];
            if (o == null) return null;      
            else{
                if (o.toString().equals("false"))
                    return new Boolean(false);
                else if (o.toString().equals("true"))
                    return new Boolean(true);
                else
                    return o.toString();
        public JViewport getViewport(){
            return viewport;
        public void selectionMultiple(boolean b){
            if (b)
                table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
            else
                table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        * Delegacion del evento 'ListSelection' que tiene lugar cuando un valor es cambiado.
        * @param event - evento de 'ListSelection'.
        public void valueChanged(ListSelectionEvent event){
            ListSelectionModel lsm = (ListSelectionModel) event.getSource();
            if (!lsm.isSelectionEmpty())
                    int selectedRow = lsm.getMinSelectionIndex();
        public void showInfo(String tittle){
            System.out.println("\n-------------------------------\n" + tittle + " : ");
            /*Accedim al objecte JTable que hi ha al JViewport*/
            System.out.println("showInfo: elperlaTableModel: Dentro de viewport. ");
            System.out.println(viewport.getComponent(0).getClass().toString());
            JTable table = (JTable)viewport.getComponent(0);
    }Finally, my problem is this.
    This Table Model works OK but when in the aplication I want to check or uncheck the cell that has the boolean data (but print with a great check box) I can't.
    Previosly I made this column editable with the setEditableColumn() method of my Table Model but in the table it don't change. If the initial value is false, that cell always be false (unchecked box) or inverse.
    How I can make this cell can be check and unchecked?
    THANKS A LOT.
    Message was edited by:
    Kefalegereta
    Message was edited by:
    Kefalegereta

    I made my own Table Model with this simple characteristicsWhy go to all that trouble. The DefaultTableModel will work. Just override the methods you want to change. Don't create a whole new TableModel.
    The problem is that you are storing the strings "true" and "false" in your table. You should be storing Boolean.TRUE and Boolean.FALSE.
    Read the Swing tutorial on using tables for a working example.

  • Not firing setValueAt() in the TableModel

    Hi All,
    I have a JTabbedPane which contains 6 Tabs and each Tab contains a JTable. A table may have JTextFieldcelleditor , JCheckBoxcelleditor...
    I entered a value in the JTextFieldcelleditor of first Tab.
    and immediately ...I am changing from first Tab to second Tab, then entered value is not set with the TableModel i,.e setValueAt() of My TableModel is not firing...
    Regards,
    Ananth

    set
    yourtable.putClientProperty("terminateEditOnFocusLost",
                             Boolean.TRUE);for all tables and the values are set when changing tabs.
    EDIT: :shakefist: @ mac ! ;-)

  • How to display previously entered data in TableModel

    This post is continued from the last one. I was having problem displaying previously entered data into TableModel. someone suggested whether my TableModel is persistent.
    I am sorry to say I am not sure how to make TableModel persistent. Can someone tell me what to do.
    Following is my implementation of TableModel:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.*;
    import java.io.*;
    public class UsersModel implements TableModel {
    public static final String[] colNames ={
    "Usernmae",
    "Location"
    public static final Class[] colClasses ={
    String.class,
    String.class,
    public static final int
    USERNAME_COL = 0,
    LOCATION_COL = 1;
    //used to hold a list of TableModelListeners
    protected java.util.List tableModelListeners = new ArrayList();
    protected java.util.List data = new ArrayList();
    public static void main(String []args){
    new UsersModel();
    }//end main
    public UsersModel(){
    public void add(Users u){
    data.add(u);
    and when I need to add new users, I do it in the following way:
    Users u= new Users(n,l);
                        model.add(u);
                                  table.setModel(model);
    I hope someone can help

    Please post the entire class, this certainly won't compile because it does not implement all the TableModel methods. Also, why not base it off of AbstractTableModel?

  • TableModel with SORT and GROUP BY functions solution.

    Hello all,
    I'd like to represent an EnvelopeTableModel. This class is developed to incapsulate another TableModel and allow user to reorder and group data without changing original values and orders.
    It allows to perform multi column sortings and grouping and
    supports following group functions: EMPTY, COUNT, MIN, MAX, SUM, AVG.
    Here you can download the library, demo version and documentation.
    http://zaval.org/products/swing/
    It would be great to know all your opinions.
    With best regards
    Stanislav Lapitsky

    About 1) and 3).
    These suggestions are almost the same. These features will change GUI component but i want to improve TableModel instead of JTable.
    Using the model user can use JTable for data representation.
    Of course I can improve JTable component and add multiline row/column headers with ability to reorder/group data from component and a lot of another widgets but it isn't my goal.
    About 2) What do you mean "crosstab"?
    Thanks for your 2-cents :-).
    With best regards
    Stas

  • How to use TableModel ???????

    I'm new to java, please help me
    i have this problem. When i choose the item in the combo box for the first time, i get the selected table, but when i choose the other item in combo box, the previous table is still remain in the panel instead of the new one.
    String sList[] =
    "InformationTechnology",
    "Account",
    "Investment"
    combo = new JComboBox();
    combo.setBounds( 220, 35, 260, 25 );
    panel3.add( combo );
    combo.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
    System.out.println("Selected Item = "+(String)combo.getSelectedItem());
    TableDisplay((String)combo.getSelectedItem());=
    try {
    // get column heads
    ResultSetMetaData rsmd = rs.getMetaData();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    columnHeads.addElement( rsmd.getColumnName( i ) );
    // get row data
    do {
    rows.addElement( getNextRow( rs, rsmd ) );
    } while ( rs.next() );
    // display table with ResultSet contents
    table = new JTable( rows, columnHeads );
    scroller = new JScrollPane(table);
    scroller.setBounds( 220, 70, 260, 100 );
    panel3.add(scroller);
    table.validate();
    catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
    just now got a 'guru' told me to use TableModel, but i search the web already but still stuck in the middle, because i don't know how to use TableModel..............

    liml,
    You code shows table instantiation as:
    // display table with ResultSet contents
    table = new JTable( rows, columnHeads );
    Check that it's in scope, say at class-level, for subsequent manipulations.
    --A                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • TableModel with 'getRowClass()' instead of 'getColumnClass()'

    Folks, I have a JTable with only a header and 2 rows. The first row should display String-info and the second should have checkboxes (Holds Boolean objects).. the problem is the TableModel interface only has a method for the column-class and that won't work for me.. The last thing I want is to do a CellRenderer and CellEditor for 'String' and 'Boolean' type of objets since they already exist.. any possibility I might workaround this problem without doing it the 'hard way'?

    Subclass JTable to adjust renderer behavior?? Ack...
    Remember, a renderer can make its decision on what to display based on any criteria it feels is necessary. The row index, the column index, the phase of the moon if you want.
    This is similar to cases where I have something similar to a IDE property list...some table cells are String, some are Boolean, etc.
    Two importants points: First, a renderer does not HAVE to be a JLabel or a JCheckBox or whatever since it returns the component to rubber stamp in the get..Component call. Because of this, I have used a pattern where I might aggregate a number of renderers as private variables and forward the request of to one of them, as appropriate. Second, if all you care about are utilizing the default renderers. Your code is as simple as forwarding it off using the JTable.getDefaultRenderer method.

  • Using the same TableModel with different tables

    hi,
    is it possible to have a TableModel class that I could use to display different columns in different tables?
    For example, suppose I have a TableModel containing user info (user_id, user_name, user_address) and I wanted to display (user_name, user_address) in one table, but just (user_id) (or even (user_id, user_name) in another).
    If this is possible, what are some good design ideas?
    thanks,
    paul

    hi,
    and thanks for your reply.
    I've checked the api but I can't see how one "flips" such a switch.
    Does there actually exist a "public void flipModelSwitch()" method? :-)
    More seriously, precisely how do I do this?
    paul

  • Changing TableModel on row selection

    I have a JTable in which selecting a new row which represents a single item, should cause other rows to be dynamically added and removed. These other rows represent details of the selected item. Only one item can be selected at a time, and subsequently, only one set of details is ever shown. The detail rows can also be selected and edited and doing so may cause additional detail rows to be created below the selected item. There are lots of custom editors and renderers involved as well.
    This dynamic model is wreaking havoc with cell editing and cell selection. I have implemeted a solution but I do not like the look of it and wonder if there is something I am missing.
    My solution required that the currently selected item or detail be stored in the TableModel. I then overrode JTable's changeSelection() method (class names are imaginary):
    public void changeSelection(int row, int column, boolean toggle, boolean extend) {
            ItemOrDetail rowItem = (ItemOrDetail)getModel().getValueAt(row, column);
            getModel().setSelectedItem(getModel().getItemForRow(row));
            row = getModel().indexForItem(rowItem);
            super.changeSelection(row,column,toggle,extend);
            setEditingRow(row);
    }So, the code gets the item or detail at the row to be selected, sets the selected Item in the model, and then asks the model what the row should now be and calls the superclass changeSelection() implementation with the adjusted row. At this point, the editor wants to appear where the selection would have been if the model hadn't changed, so setEditingRow() is called to adjust it to the proper row.
    The setSelectedItem() method removes the old detail rows, calls fireTableRowsDeleted() adds the new detail rows and calls fireTableRowsInserted().
    Modifying the model inside changeSelection() just seems wrong. However, creating a Mediator object that listens for selection changes and then tweaks the model doesn't work because the editors are rendered before the selection is updated.
    There are various overridable methods inside JTable that seem like they may be part of a better solution, but it is not evident to me what that solution is.
    If anyone (this means you Kleopatra...:) ) has any thoughts on this matter, I would appreciate your comments.
    Jim S.

    This sounds to me like a 'parts explosion' view which is nomally best done through a JTree. Though I have never used it, http://java.sun.com/products/jfc/tsc/articles/treetable1/index.html might be applicable

  • Help on customized TableModel please !!!!!!

    hi there
    i need to add a row at runtime, some people suggested me extend abstractTableModel to accomplish this. here is my tableModel:
    class CustomTableModel extends AbstractTableModel
    Vector rowData, columnNames;
    public CustomTableModel(Vector rowData, Vector columnNames)
    this.rowData = rowData;
    this.columnNames = columnNames;
    public void addRows(String n)
    Vector tmp = new Vector();
    tmp.add(n);
    rowData.add(tmp);
    fireTableDataChanged();
    public void removeRows()
    rowData.removeElement(rowData.lastElement());
    fireTableDataChanged();
    public int getColumnCount()
    return columnNames.size();
    public int getRowCount()
    return rowData.size();
    public boolean isCellEditable(int row, int col)
    return true;
    public String getColumnName(int idx)
    return (String)columnNames.elementAt(idx);
    public Object getValueAt(int row, int col)
    return ((Vector)rowData.elementAt(row)).elementAt(col);
    public void setValueAt(Object value, int row, int col)
    ((Vector)rowData.elementAt(row)).setElementAt(value, col);
    fireTableCellUpdated(row, col);
    in the run() of my runnable class, here is what i add the row
    public void run()
    int rowCounter = 1;
    boolean okay = true;
    SimpleDateFormat format = new SimpleDateFormat("H:mm:ss:SSS");
    while (okay)
    try
    tablemodel = (CustomTableModel)jTable.getModel();
    //just add a time stamp to the new cell
    tablemodel.addRows(format.format(new Date()).toString());
    //trying to repack the pane, not sure if this is ok?????
    jScrollPane = new JScrollPane(jTable);
    jScrollPane.setPreferredSize(new Dimension(480, 160));
    jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    p.removeAll();
    p.add(jScrollPane);
    p.revalidate();
    Thread.sleep(1000);
    ++rowCounter;
    catch (InterruptedException e)
    okay = false;
    but when i test it. the exception occured with following message
    Exception occurred during event dispatching:
    java.lang.ClassCastException: java.lang.String
         at monitor.CustomTableModel.getValueAt(TimeTable.java:154)
         at javax.swing.JTable.getValueAt(JTable.java:1714)
         at javax.swing.JTable.prepareRenderer(JTable.java:3533)
         at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:995)
         at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:917)
         at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:858)
         at javax.swing.plaf.ComponentUI.update(ComponentUI.java:39)
         at javax.swing.JComponent.paintComponent(JComponent.java:395)
         at javax.swing.JComponent.paint(JComponent.java:687)
         at javax.swing.JComponent.paintChildren(JComponent.java:498)
         at javax.swing.JComponent.paint(JComponent.java:696)
         at javax.swing.JViewport.paint(JViewport.java:668)
         at javax.swing.JComponent.paintChildren(JComponent.java:498)
         at javax.swing.JComponent.paint(JComponent.java:696)
         at javax.swing.JComponent.paintChildren(JComponent.java:498)
         at javax.swing.JComponent.paint(JComponent.java:696)
         at javax.swing.JComponent.paintWithBuffer(JComponent.java:3878)
         at javax.swing.JComponent._paintImmediately(JComponent.java:3821)
         at javax.swing.JComponent.paintImmediately(JComponent.java:3672)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:370)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:124)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:154)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:337)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)
    can anyone help me to point the problem? thank you.

    thank you all for your help.
    if i extend DefaultTableModel, do i need to implement the addRow() method?
    in the run() method, can i do the following to add a row to the table:
    public void run()
    int rowCounter = 1;
    boolean okay = true;
    SimpleDateFormat format = new SimpleDateFormat("H:mm:ss:SSS");
    while (okay)
    try
    //get the model and use it to add rows to the table???????
    tablemodel = (DefaultTableModel)jTable.getModel();
    tablemodel.addRows();
    //trying to repack the pane, not sure if this is ok?????
    jScrollPane = new JScrollPane(jTable);
    jScrollPane.setPreferredSize(new Dimension(480, 160));
    jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    p.removeAll();
    p.add(jScrollPane);
    p.revalidate();
    Thread.sleep(1000);
    ++rowCounter;
    catch (InterruptedException e)
    okay = false;
    can i directly work on the model to modify the table? thank you.

  • Storing data in  tablemodel to a binary  file

    hi,
    i have a program that uses AbstractTableModel with Jtable....I need to store data in a file when the program closes... i heard that there is a way to some how convert data in Tablemodel to a binary file and retrieve data from the binary file...other then storing it in a text file and parsing the data. So can anyone help me?
    Thanks

    You can loop through the data in the table and Serialize the data using object serialization.
    Simply implement the java.io.Serializable interface. Then use this code for serizlizing the data. Note that to serialize data, it must be an object not primitive types.
    serialize to a binary file
    try
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(new File("datastore.ser")));
        os.writeObject(<your data from table>);
        os.flush();
    catch (IOException ioe) { ioe.printStackTrace(); }
    reconstructing the object from binary file
    try
        ObjectInputStream is = new ObjectInputStream(new FileInputStream(new File("datastore.ser")));
        obj = (<data type of Object>) is.readObject();
    catch (IOException ioe)
        ioe.printStackTrace();
    }Hope this helps,
    Riz

  • Best method to fill in tablemodels getColumnClass

    Hello,
    in my application i have several JTables. The data represented on it is derived from a database. Some columns are booleans, but because my database doesn't support booleans I use VARCHAR(1) which is a String in Java.
    All my tables are using a tablemodel which extends the DefaultTableModel. I want the booleans to be represented as a checkbox in my JTable.
    1) Where is the best place to convert the string values to boolean values (I suppose somewhere in the tablemodel) ?
    2) To get the classes of my columns I can derive them from the database itself. But should i get them every time the getColumnClass() is called or should I load them when I create my tablemodel?
    What would be the best approach here?
    I ask these questions because I know that you must be careful when changing the tablemodel to avoid that you tables are becoming slow.

    1) Convert the data when you add it to the TableModel so its only done once.
    2) The Object added to the TableModel is of the correct class. You could create an array that stores the class of each column when you create the model, but from a speed point of view this isn't as important as efficient rendering code. If all your columns will have non-null data then you could just use generic code like this:
                public Class getColumnClass(int column)
                    for (int row = 0; row < getRowCount(); row++)
                        Object o = getValueAt(row, column);
                        if (o != null)
                            return o.getClass();
                    return Object.class;
    I know that you must be careful when changing the tablemodel to avoid that you tables are becoming slowThen main concern here is for rendering of each cell. The data is only loaded into the model once so that why you would do all the conversion up front. However renderering of each cell is done much more frequently, every time you change the selection of a row, two rows get repainted. Every time you scroll multiple rows get painted. So the bigger concern is the the renderer is very efficient and doesn do an unnecessary processing.

Maybe you are looking for

  • Profit Center Accounting in BCS

    Dear Experts, I'm going to have Profit Center based consolidation reporting in SEM-BCS. Since I'm using NewGL (with segmented Profit Center), I don't have to activate Profit Center Accounting Module. Is it possible to have Profit Center based consoli

  • Frequent JVM freeze/crash

    From time to time our system freezes (can be after days or hours). We have been running on 1.5.0_04 and 1.5.0_05 both client and server (on x86 machine). We have a lot of file IO and other JNI (custom) calls. We've been trying many thing to get it go

  • 5800 files deleted from mem card in mass storage -...

    I have connected my phone via USB mass storage and deleted some MP3s however there is no extra free space showing on the phone (in File Manager) I had this problem before and it somehow fixed it self after a reboot/sync, but this time it isn't workin

  • 0210: Stuck Key 4E

    has anyone ever seen this message? We get it right after the bios screen. It will not allow the system to boot. It ONLY occurs on the docking station, replaced the dock and still get the same issue.

  • Convert dmp to ascii

    I do not have oracle, but I have a dump file that I want to extract some data from. Is there a tool available to convert the dmp file to ascii or excel...?