Updating a JTable when using an AbstractTableModel

Hi,
I have tried to create a JTable with an AbstractTableModel but I am obviously missing something in all the tutorials and examples as I cannot get the table to update when using my model.
My application reads data in from a CSV file that is selectable at run time, but I have written a small app that demonstrates the problem I am having.
If you uncomment the DefaultTableModel lines of code all is OK, but I need to use my Abstract Class as I intend to colour certain rows and add a Boolean column, that I would like to display as a CheckBox and not just the String representation.
Any help would be great as I am tearing my hair out here!!
My Test Class
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
public class TestTable extends JFrame implements ActionListener
private JPanel jpTestTable = new JPanel();          
private Vector vColumnNames = new Vector();
private Vector vCellValues = new Vector();
private DefaultTableModel dtmTestTable;
private CustomTableModel ctmTestTable;
private JTable jtTestTable;
private JScrollPane jspTestTable;
private JButton jbGo = new JButton();
     public TestTable()
     dtmTestTable = new DefaultTableModel();
     ctmTestTable = new CustomTableModel();
     //jtTestTable = new JTable( dtmTestTable );  //using this instead of my CustomModel works fine
     jtTestTable = new JTable( ctmTestTable );
     jtTestTable.setAutoCreateRowSorter(true);
     jtTestTable.setFillsViewportHeight( true );
     jspTestTable = new JScrollPane( jtTestTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
     jspTestTable.setBounds( 10, 10, 350, 400 );
     jspTestTable.setBorder( BorderFactory.createLoweredBevelBorder() );
     jbGo.setText( "Go" );
     jbGo.setBorder( BorderFactory.createRaisedBevelBorder() );
     jbGo.setBounds( 125, 430, 100, 25 );
     jbGo.addActionListener(this);
     jpTestTable.setLayout( null );
     jpTestTable.setBounds( 0, 0, 375, 500 );     
     jpTestTable.add( jspTestTable );
     jpTestTable.add( jbGo );
     this.setTitle( "Test Table" );
     this.getContentPane().setLayout( null );
     this.setBounds( 200, 50, 375, 500 );
     this.getContentPane().add( jpTestTable );
     this.setResizable( false );
     public void actionPerformed( ActionEvent e )
     updateTable();
     public void updateTable()
     vColumnNames.add( "Please" );
     vColumnNames.add( "work" );
     vColumnNames.add( "you" );
     vColumnNames.add( "git!" );
     vColumnNames.trimToSize();
     Vector vRow = new Vector();
          for( int i = 0; i < 10; i++ )
               for( int x = 0; x < vColumnNames.size(); x++ )
                    vRow.add( "" + i + "" + x );
          vCellValues.add( vRow );
     //dtmTestTable.setDataVector( vCellValues, vColumnNames );  //using this instead of my CustomModel works fine
     ctmTestTable.setDataVector( vCellValues, vColumnNames );
     public void processWindowEvent(WindowEvent e)
     super.processWindowEvent(e);
          if(e.getID() == WindowEvent.WINDOW_CLOSING)
          exit();
     public void exit()
     System.exit( 0 );     
     public static void main(String args[])
     TestTable tt = new TestTable();
     tt.setVisible( true );
}And my CustomTableModel Class
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.*;
public class CustomTableModel extends AbstractTableModel
protected Vector columnIdentifiers  = new Vector();
protected Vector dataVector = new Vector();
     public CustomTableModel()
     public CustomTableModel( Vector data, Vector columnNames )
     setDataVector( data, columnNames );
     public int getColumnCount()
     return columnIdentifiers.size();
     public int getRowCount()
     return dataVector.size();
     public String getColumnName( int col )
     return "" + columnIdentifiers.get( col );
     public Object getValueAt( int row, int col )
     Vector vRow = new Vector();
     vRow = (Vector) dataVector.get( row );
     return (Object) vRow.get( col );
     public Class getColumnClass(int c)
     return getValueAt(0, c).getClass();
     public boolean isCellEditable(int row, int col)
          if (col < 2)
               return false;
          else
               return true;
     public void setValueAt( Object value, int row, int col )
     Vector vTemp = (Vector) dataVector.get( row );
     Vector<Object> vRow = new Vector<Object>();
          for( int i = 0; i < vTemp.size(); i++ )
               vRow.add( (Object) vTemp.get( i ) );
     vRow.remove( col );
     vRow.add( col, value );
     vRow.trimToSize();     
     dataVector.remove( row );
     dataVector.add( row, vRow );
     dataVector.trimToSize();
     fireTableCellUpdated(row, col);
     public void setDataVector( Vector data, Vector columnNames )
     columnIdentifiers  = (Vector) columnNames.clone();
     dataVector = (Vector) data.clone();
     fireTableDataChanged();
}I have just tried adding the following code after reading another example, but same result - arrrrrrrgggggggghhhhhhhhh!!!!
ctmTestTable = (CustomTableModel) jtTestTable.getModel();
ctmTestTable.fireTableDataChanged();Edited by: Mr_Bump180 on Jul 28, 2008 2:51 PM

Hi camickr,
Well that is good news as my Abstact class is about as much good as an ashtray on a motorbike. I think I must have misread or misunderstood the Table Tutorials as I thought I had to use an Abstrat class to get colurs based on conditions and to get Check Boxes to represent Boolean variables.
I am clearly struggling with this concept - which I have never used before - do you know of any tutorials, that explain how to update a JTable with file data at runtime, as all the ones I have looked at set it as part of the java code - which is no good to me.
Also am I overriding the DefaultTableModel Class correctly - I have written a seperate Model class but wounder if I need to include it in with my JTable class. I was trying to make it generic so I didn't have to write one for each JTable - but as I can't get it to work I should perhaps try to walk before I run.
I'm not asking for the code, but just a guide to how close I am to where I want to be, and some links to tutorials that are closer to what I want to achieve. I will reread the Java Table Tutorial tonight - and you never know the penny may drop all on it's own this time!!!
Thanks

Similar Messages

  • Problem with checkbox in JTable when using MyTableModel

    Hi all,
    I have been trawling these message boards for days looking for the answer to my question but have not had any success.
    I am extending AbstractTabel model to create MyTableModel which returns a vector containing the results of a MySql query. One column in this query returns a "0" or "1" which I then store as the boolean value into the vector so that it is rendered as a checkbox on the screen.
    I have also overridden the setValueAt method. THe problem is that when I attempt to check the box in the table, the checkbox isn't actually checking.
    Do I need to implement some sort of listener which picks up the user clicking the box and refresh the model?
    Here is my model code:
    public class MyTableModel extends AbstractTableModel {
        private Vector v = null;
        int listId;
        MyTableModel(int listId){
            this.listId = listId;
            v = new ListItemManagement().getFullList(listId);
       public Class getColumnClass(int c) {
            switch(c) {
                case 6:
                    return Boolean.class;
                default:
                    return Object.class;
        public String getColumnName(int colIndex){
            return ((String[])v.get(0))[colIndex];
        public int getColumnCount() {
            return ((String[])v.get(0)).length;
        public int getRowCount() {
            return (v.size() - 1);
        public Object getValueAt(int rowIndex, int colIndex) {
            return ((Object[])v.get(rowIndex + 1))[colIndex];
        public void setValueAt(Object aValue, int rowIndex, int colIndex) {
            System.out.println("Value: " + String.valueOf(aValue));
            Object row[] = (Object[]) v.elementAt(rowIndex);
            if(colIndex<6){
                row[colIndex] = (String)aValue;
            else{
                row[colIndex] = (Boolean)aValue;
            v.setElementAt(row, rowIndex);
            fireTableCellUpdated(rowIndex, colIndex);
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            return ! (col < 6);
        }Here is the getFullList function which returns the vector:
                rs = stmt.executeQuery();
                ResultSetMetaData colData = rs.getMetaData();
                int columnCount = colData.getColumnCount();
                String[] columnNames = new String[columnCount];
                for (int i = 0; i < columnCount; i++){
                    columnNames[i] = colData.getColumnName(i + 1);
                Vector v = new Vector();
                v.add(columnNames);
                while (rs.next()){
                    Object[] values = new Object[columnCount];
                    for (int i = 0; i < (columnCount-1); i++){
                        values[i] = rs.getString(i + 1);
                    int sel = rs.getInt("selected");
                    System.out.println(sel);;
                    if(sel==0){
                        values[columnCount-1]=new Boolean(false);
                    else if (sel==1)
                        values[columnCount-1]=new Boolean(true);
                    v.add(values);
                rs.close();
                stmt.close();
                return v;

    Thanks for the replies, much appreciated.
    I've looked at the Swing jtable tutorial and added a TableModelListener and have managed to achieve the desired results but for one thing.
    When I attempt to check the box on the first row of the jTable I get a runtime error:
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayStoreException: java.lang.Boolean
    at project.MyTableModel.setValueAt(MyTableModel.java:65)
    I have been playing around with the setValueAt method and it is in my original post. Here is how it currently looks:
        public void setValueAt(Object aValue, int rowIndex, int colIndex) {
            System.out.println("Value: " + String.valueOf(aValue));
            Object row[] = (Object[]) v.elementAt(rowIndex);
            if(colIndex<6){
                row[colIndex] = (String)aValue;
            else{
                    if(getValueAt(rowIndex,colIndex).toString()=="true"){
                    row[6] = new Boolean(false);
                else{
                    row[6] = new Boolean(true);
            v.setElementAt(row, rowIndex);
            fireTableCellUpdated(rowIndex, colIndex);
        }

  • How to update bean properties when using an immediate link

    Hello,
    I have a page with a find link next to an input text field. The input text field requires a valid code to be entered. If the user doesn't know the code they need to press the find link to go to a search page and select the code. The input text code field needs to have a value entered so it has its required attribute set because the validator I have and attached to the input text field does not get called unless something is entered in the field. If I don't set the link to immediate the required constraint prevents the search page from being invoked but if I do set it to immediate the values typed on the page are not updated to the bean properties they are bound to.
    I have read many posts but I fail to see a way to resolve this. The update model phase is apparently skipped because of the immediate attribute and so the values typed in by the user are lost.
    Please help.
    Thanks,
    Randall

    A UIInput holds the submitted value.
    When updating models it is cleared to null but when some error occurs it keeps to hold the submitted value.
    The TextRenderer uses the submitted value if the value is null.
    Therefore, you can see the submitted value is redrawn when some error occurs.
    Unfortunately, this mechanizm does not work beyond requests
    because the default application action listener always create a new viewroot based on the navigation rules.
    An general solution of your problem is not so easy.
    I think it may be to customize the action listener or the lifecycle.
    A temporal solution may be that the link action copys the submitted value to the managed-beans.

  • Why do application updates continually fail when using AAM

    For more than a week I have tried to use AAM to update 17 applications in need of bug fixes. Of those 17 I have had success with only one application, Acrobat XI Pro. I have attempted with about half a dozen others and they all fail about midway through the download process.
    I am ending my 1 year subscription period and I am seriously considering not renewing my subscription. Getting help is very difficult indeed.

    UrSphere are you receiving any specific error messages when attempting to install the updates?  If it is U44M1P7 then this simply means the update has failed.  To locate the root cause of the failure you will want to review the installation logs for the update.  This will allow you to locate the specific error which is preventing the updates from being applied successfully.
    Please see Installation failed. Error U44M1P7 | Updates - http://helpx.adobe.com/creative-suite/kb/error-u44m1p7-installing-updates-ccm.html for information on how to resolve the U44M1P7 error.  The document also references how to locate and interpret the installation log files.  Please feel free to post any specific errors you discover to this discussion.

  • Problem in updating IMRG table when using MEASUREM_DOCUM_RFC_SINGLE_001

    Hi experts,
                   I am using MEASUREM_DOCUM_RFC_SINGLE_001 to create measuring documents for the equipment assigned to a functional location. But when i used this in ECC 5.0 the table IMRG  is updated rightly. Now i am using the same in ECC 6.0 , I observe that the following fields of IMRG table are not get updated when compared with 5.0:
    CNTRG
    CNTRR
    CNTRRI
    CDIFF
    CDIFFI
      IDIFF
    Can any one tell what could be the problem.

    Check for  Sap notes for Function module MEASUREM_DOCUM_RFC_SINGLE_001.
    And apply SAP notes correctly according to patch levels.

  • Set focus on particular cell in a JTable when using TableModel.

    I want to implement validation in my table cells. I the value does not satisfy certain condition then the focus should remain on the same cell and the user should be asked to enter valid value.
    I am using TableModel and i have tried implementing validation in the setValueAt() method some thing like this.
    setValueAt method of my table model.
    public void setValueAt(Object value, int row, int col){
    if(datalist.size()>row){
    OutboundFieldMappingObj obj=(OutboundFieldMappingObj)datalist.get(row);
    String str=null;
    switch (col){
    case 0:
    str=Validator.getValidNumber((String)value,1,999999999L);
    obj.setFiledName(str);
    break;
    case 1:
    str=Validator.getValidString((String)value,128,false);
    obj.setFiledClass(str);
    break;
    case 2:
    obj.setSource((String)value);
    break;
    fireTableCellUpdated(row, col);
    But this doesn't solve the issue. In this case after entering the value when i click on some other cell then it shows me a message stating that the value is invalid but it doesn't takes the focus back to same cell. The focus is shifted to the cell where i have clicked.
    Please help me out in resolving the issue.
    I have added the code of my validator class at the bottom if any one needs to have a look at it.
    Thanks
    Validator class
    public class Validator {
    public Validator() {
    public static String getValidString(String val, int max, boolean upper) {
    if (val == null || val.equals("")) {
    showErrorMsg("The cell can not be left blank");
    return " ";
    if (val.length() > max) {
    val = val.substring(0, max);
    showErrorMsg("String value to long. Truncated to " + max +" characters.");
    if (upper) {
    val = val.toUpperCase();
    return val;
    public static String getValidNullableString(String val, int max, boolean upper) {
    if (val == null) {
    return null;
    if (val.length() > max) {
    val = val.substring(0, max);
    showErrorMsg("String value to long. Truncated to " + max +" characters.");
    if (upper) {
    val = val.toUpperCase();
    return val;
    public static String getValidNumber(String number, int min, long max) {
    try {
    long num = Long.parseLong(number);
    if (num < min) {
    showErrorMsg("Number less than mininum value of " + min + ".");
    return "" + min;
    if (num > max) {
    showErrorMsg("Number greater than maximum value of " + max +".");
    return "" + max;
    return number;
    } catch (Exception x) {
    showErrorMsg("Invalid Entry. Number Expected.");
    return "0";
    // return "";
    public static boolean getValidNumber(String number) {
    try {
    Integer.parseInt(number);
    return true;
    } catch (Exception x) {
    showErrorMsg("Invalid Entry. Number Expected.");
    return false;
    // return "";
    public static void showErrorMsg(String message) {
    JOptionPane.showMessageDialog(new java.awt.Frame(), message,
    "Invalid Value!",
    JOptionPane.ERROR_MESSAGE);
    public static boolean validString(String str) {
    if (str != null && str.length() > 0) {
    return true;
    return false;
    }

    You need to create a custom editor. Something like this:
    http://forums.sun.com/thread.jspa?forumID=57&threadID=642364
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • Dictation is no longer possible after updating to iOS8, when using Pages. I am able to dictate this question in Safari, but hey Pages will not let me dictate.

    I updated to I OS 8, and after I did I discovered that capital Pages no longer accepted dictation. Instead when the keyboard was supposed to slide up and I pressed the mic button, everything disappeared below the line. There was no audio line, there was no keyboard, there was no DONE button. The only way that I could get out of the program was to hit the home button.

    I am assuming you got that message when attempting to post an old thread. The old post is probably locked/archived.
    FYI, posting on old threads usually yields no responses at all.
    I have requested that this post be moved to the iPhone forum where you might get assistance.
    Barry

  • My dvd player fails since updating to mavrick when using external projector. Help?

    Works when not connected perfectly

    In addition to RRFS's advice, please post in the correct forum. This forum is for iMac's, you mentioned you have a MacBook Pro. They're similar but still pretty different hardware.

  • Wont update application when using itunes

    i cant update my apps. when using itunes,
    i update all my apps on itunes but when i apply it on my phone it wont take effect??
    PLS HELP!! >.<

    Are you able to update the apps using the App Store on your iPhone? 

  • Page culture changes when using AsyncPostBackTrigger

    In my web application I have used an asp timer and a AsyncPostBackTrigger, and in content template I use a datagrid. and in timer
    tick event I update the grid, when using the AsyncPostBackTrigger, the culture of the datagrid changes to default, how can i avoid this?

    Please post questions related to ASP.NET in the ASP.NET forums (http://forums.asp.net ).

  • Updating a JTable using CachedRowSet data

    Hello, I would like to know how I can update my already created JTable receiving data from a CachedRowSet without creating a new table model (this is the method I have been using). I have read about using the fireTableDataChanged() method but I cant figure out how to use this works. Maybe an explanation on how the information in the CachedRowSet is updated in the JTable when notifiers are used will help.
    Any help will be appreciated

    camickr wrote:
    table.setAutoCreateColumnsFromModel( false );
    Perfect. This works well for my issue. I can now use the setModel() method without having the columns reordered.Damn camickr, that is a bloody good thing to know (it's often so much easier to recreate the table model, here's a very neat solution to one of the pitfalls)! Thanks :)
    Since this is solved, I still want to know how I can use the fireTableDataChanged() method and AbstractTableModel interface with CachedRowSet (just out of curiosity). I have been looking through jduprez's suggestion to figure this out too. I am currently faced with the issue,
    I have two classes, one for the CachedRowSet and the other with the table implementationsAs you describe it, I don't think that's a good approach: what I meant wad an implementation of TableModel , not a subclass of JTable : the stock JTable already knows how to work with any model implementation, as long as it implements TableModel .
    Where do I need to use the AbstractTableModel interface?It is a class, not an interface: it implements TableModel and provides useful defaults for some methods (at least, the management of the list of TableModelListener )
    My suggestion was that you define a custom class that extends AbstractTableModel , and uses its fireXxx judiciously.
    here is an example:
    public class RowSetAwareTableModel extends AbstractTableModel {
        public void setUpdateddata(RowSet newData) {
            this rowSet = newdata;
            super.fireTabledataChanged();
        /** Implementation of TableModel */
        public int getRowCount() {
            return rowset.getMaxRows();
        // etc...
    }

  • Updating a JTable using a JTable

    I am looking to update an empty JTable using the data from a JTable containing a set of data.
    I am aware that addRow can be used with the DefaultTableModel from previous discussions on this forum, but I have found this call isn't available when using AbstractTableModel.
    The reason I have been having some problems with this as it is necessary for the AbstractTableModel to be used in the context of the GUI, and I am asking if there is a way to solve this using the AbstractTableModel?
    I am using an AbstractTableModel for both the data table and the table showing all currently and previously selected rows.

    I am using an AbstractTableModel for both the data table and the table showing all currently and previously selected rows.No you aren't. You can't create an Abstract class because not all the methods are implements. You are using a class that extends AbstractTableModel.
    So why not use the DefaultTableModel and make your life simple?

  • Using Adobe Photoshop CS2 version 9 and have updated it, but when stacking photos, it comes up with PSD, whereas I want Jpeg, and I change the format to Jpeg and the box then comes up with cannot save as there is a program error. Be very grateful for help

    Using Adobe Photoshop CS2 version 9 and have updated it, but when stacking photos, it comes up with PSD, whereas I want Jpeg, and I change the format to Jpeg and the box then comes up with cannot save as there is a program error. Be very grateful for help with this, please.

    jpg does not support Layers.
    Just to make sure, what exactly do you mean by "stacking photos" and what do you want to achieve thereby?

  • Firefox won't open following update. Can't open Profile Mgr, even when using entire directory path in cmd line

    I'm running Firefox on a Windows 7 machine. Firefox won't open following the latest update. I've read the help articles and it seems like I need to create a new profile because my settings have likely been corrupted. I'm unable to open Profile Mgr, even when using entire directory path in cmd line. I've tried the following commands in the command line:
    firefox -p
    "C:\Program Files (x86)\Mozilla Firefox\firefox.exe" -p
    Nothing happens with either command.
    I'm also running Norton Internet Security. I read a help article Re Virtual Browsing features possibly causing a problem. The article said to check the virtualization setting in the internet security software and to clear the virtual cache. I went thru all of the settings menus in Norton Internet Security version 21.6.0.32 and I didn't see anything that looked like 'virtualization" settings, so I assumed that this doesn't apply to me.
    If you have any ideas, I'd sure appreaciate your expertise!!

    ''arcandl [[#question-1038482|said]]''
    <blockquote>
    I'm running Firefox on a Windows 7 machine. Firefox won't open following the latest update. I've read the help articles and it seems like I need to create a new profile because my settings have likely been corrupted. I'm unable to open Profile Mgr, even when using entire directory path in cmd line. I've tried the following commands in the command line:
    firefox -p
    "C:\Program Files (x86)\Mozilla Firefox\firefox.exe" -p
    Nothing happens with either command.
    I'm also running Norton Internet Security. I read a help article Re Virtual Browsing features possibly causing a problem. The article said to check the virtualization setting in the internet security software and to clear the virtual cache. I went thru all of the settings menus in Norton Internet Security version 21.6.0.32 and I didn't see anything that looked like 'virtualization" settings, so I assumed that this doesn't apply to me.
    If you have any ideas, I'd sure appreaciate your expertise!!
    </blockquote>
    ''philipp [[#answer-670108|said]]''
    <blockquote>
    hello arcandl, when firefox isn't launching after you double-click on the shortcut this is sometimes also a sign of malware being active on a system.
    you might want to try running a scan with some different other security tools like the [http://www.malwarebytes.org/products/malwarebytes_free free version of malwarebytes] and [http://www.bleepingcomputer.com/download/adwcleaner/ adwcleaner] which are specialised in removing adware and browser hijackers.
    [[Troubleshoot Firefox issues caused by malware]]
    </blockquote>
    Phillip - You're a genius!!! I ran malwarebytes and it resolved my problem. Thank you so much!!!

  • How do I delete an old Apple ID and still update apps purchased when I was using it?

    How do I delete an old Apple ID and still update apps purchased when I was using it?

    One, you cannot delete an Apple ID, all you can do is stop using it and let it fade away.
    Two, apps are permanently tied to an aPple ID and can never be transferred to another.  You must use that same ID to update an app, or delete the app and repurchase/download under another ID.

Maybe you are looking for