Table model question

How can I know the exact rows/columns that need to be rendered by a jtable before getvalueat is called from the model?
The purpose is to create a progress bar because some the of code in my tablemodel getvalueat() may take a long time.

Override JTable and the method prepareRenderer(TableCellRenderer renderer, int row,int column). This is the method that actually calls getValueAt. Override it something like this:
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
    // Do your logic first
    // Allow super to do its thing, which will call getValueAt
    return super.prepareRenderer( renderer, row, column );
}However, I don't think this will accomplish what you want. getValueAt (and the above method) are called A LOT, and not just when the table is first populated. Put a system.out in the method above just to see how often (move the mouse around for example once it is loaded). NOTE: If every call to getValueAt is slow for your model, your table's terrible performance will make it unusable.
It would be better to have your TableModel control the progress since it is really the only one that knows what is going on with the data anyway.

Similar Messages

  • A question about table model

    I created a table model and use JTable to display content of a database's table with that model.
    The problem is: when I update a data to data1 in a cell (first column) and hightlight another cell (second column), all cells of first column change content to data1. What 's the problem with my table model?
    import java.util.Vector;
    import java.sql.*;
    import javax.swing.table.AbstractTableModel;
    public class CommonTableModel extends AbstractTableModel {
    String[] columnNames;
    Vector          rows, newRow;
    ResultSetMetaData metaData;
    private boolean editable;
    public CommonTableModel(ResultSet rs, boolean editable) {
    this.editable = editable;
    try {
    metaData = rs.getMetaData();
    int numberOfColumns = metaData.getColumnCount();
    columnNames = new String[numberOfColumns];
    for(int column = 0; column < numberOfColumns; column++) {
    columnNames[column] = metaData.getColumnName(column+1);
    rows = new Vector();
    newRow = new Vector();
    while (rs.next()) {
    for (int i = 1; i <= getColumnCount(); i++) {
         newRow.addElement(rs.getObject(i));
    rows.addElement(newRow);
    } catch (SQLException ex) { System.err.println(ex);}
    public int getColumnCount() { return columnNames.length; }
    public int getRowCount() { return rows.size();}
    public String getColumnName(int column) { return columnNames[column];}
    public Object getValueAt(int row, int column) {
         newRow = (Vector)rows.elementAt(row);
         return newRow.elementAt(column);
    public Class getColumnClass(int column) {
         return getValueAt(0, column).getClass();
    public boolean isCellEditable(int row, int column) {
         if (column == 0) { return false; }
         return editable;
    public void setValueAt(Object value, int row, int column) {
         newRow = (Vector)(rows.elementAt(row));
         newRow.setElementAt(value, column);
         fireTableCellUpdated(row, column);
    }

    Try this :
    rows = new Vector();
    //newRow = new Vector();
    while (rs.next()) {
        newRow = new Vector(); // it must be here
        for (int i = 1; i <= getColumnCount(); i++) {
            newRow.addElement(rs.getObject(i));
        rows.addElement(newRow);
    }Denis

  • Calc problem with fact table measure used as part of bridge table model

    Hi all,
    I'm experiencing problems with the calculation of a fact table measure ever since I've used it as part of a calculation in a bridge table relationship.
    In a fact table, PROJECT_FACT, I had a column (PROJECT_COST) whose default aggregate was SUM. Whenever PROJECT_COST was used with any dimension, the proper aggregation was done at the proper levels. But, not any longer. One of the relationships PROJECT_FACT has is with a dimension, called PROJECT.
    PROJECT_FACT contains details of employees and each day they worked on a PROJECT_ID. So for a particular day, employee, Joe, might have a PROJECT_COST of $80 for PROJECT_ID 123, on the next day, Joe might have $40 in PROJECT_COST for the same project.
    Dimension table, PROJECT, contains details of the project.
    A new feature was added to the software - multiple customers can now be charged for a PROJECT, where as before, only one customer was charged.
    This percentage charge break-down is in a new table - PROJECT_BRIDGE. PROJECT_BRIDGE has the PROJECT_ID, CUSTOMER_ID, BILL_PCT. BILL_PCT will always add up to 1.
    So, the bridge table might look like...
    PROJECT_ID CUSTOMER_ID BILL_PCT
    123          100     .20
    123          200     .30
    123          300     .50
    456 400 1.00
    678 400 1.00
    Where for project 123, is a breakdown for multiple customers (.20, .30. .50).
    Let's say in PROJECT_FACT, if you were to sum up all PROJECT_COST for PROJECT_ID = 123, you get $1000.
    Here are the steps I followed:
    - In the Physical layer, PROJECT_FACT has a 1:M with PROJECT_BRIDGE as does PROJECT to PROJECT_BRIDGE (a 1:M).
    PROJECT_FACT ===> PROJECT_BRIDGE <=== PROJECT
    - In the Logical layer, PROJECT has a 1:M with PROJECT_FACT.
    PROJECT ===> PROJECT_FACT
    - The fact logical table source is mapped to the bridge table, PROJECT_BRIDGE, so now it has multiple tables it maps to (PROJECT_FACT & PROJECT_BRIDGE). They are set for an INNER join.
    - I created a calculation measure, MULT_CUST_COST, using physical columns, that calculates the sum of the PROJECT_COST X the percentage amount in the bridge table. It looks like: SUM(PROJECT_FACT.PROJECT_COST * PROJECT_BRIDGE.BILL_PCT)
    - I brought MULT_CUST_COST into the Presentation layer.
    We still want the old PROJECT_COST around until it get's phased out, so it's in the Presentation layer as well.
    Let's say I had a request with only PROJECT_ID, MULT_CUST_COST (the new calculation), and PROJECT_COST (the original). I'd expect:
    PROJECT_ID MULT_CUST_COST PROJECT_COST
    123          $1000     $1000
    I am getting this for MULT_CUST_COST, however, for PROJECT_COST, it's tripling the value (possibly because there are 3 percent amounts?)...
    PROJECT_ID MULT_CUST_COST PROJECT_COST
    123          $1000 (correct)      $3000 (incorrect, it's been tripled)
    If I were to look at the SQL, it would have:
              SELECT SUM(PROJECT_COST),
    SUM(PROJECT_FACT.PROJECT_COST * PROJECT_BRIDGE.BILL_PCT),
                   PROJECT_ID
              FROM ...
              GROUP BY PROJECT_ID
    PROJECT_COST used to work correctly before modeling a bridge table.
    Any ideas on what I did wrong?
    Thanks!

    Hi
    Phew, what a long question!
    If I understand correctly I think the problem lies with your old cost measure, or rather combining that with you new one in the same request. If you think about it, your query as explained above will bring back 3 rows from the database which is why your old cost measure is being multiplied. I suspect that if you took it out of the query, your bridge table would be working properly for the new measure alone?
    I would consider migrating your historic data into the bridge table model so that you have a single type of query. For the historic data each would have a single row in the bridge with a 1.0 BILL_PCT.
    Best of luck,
    Paul
    http://total-bi.com

  • Custom Table Model from Default Table Model

    I'm creating a customised table model to create a table with column header and empty rows.But it is throwing Component paint_imediatly error.If i pass in empty string to the row vector then setNumRows then no problem. If i do like this later it throws me error in my addNewRow method which was working fine before.Can anyone help?I would realy apreaciate it.Thank you.
    Kavitha

    This must be your lucky day :)
    Here is my version of an EditableTableModel which displays an emptyline as the last line
    import java.io.*;
    import java.util.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    * Custom TableModel, allows addition and removal of records/rows and editting of existing values.
    * it also keeps track over which rows have been altered.
    * column 0 is a boolean indicating wheter or not to keep this row/record
    * @author Maurice Marrink
    * @version 1.0
    public class EditableTableModel extends AbstractTableModel implements Serializable, TableModelListener
         protected ArrayList keep,changed;          //houden bij of een rij gedel moet worden en of ie is veranderd (false = delete)
         protected ArrayList[] DATA;
         protected int emptyLineIndex;
         protected String[] kolomNamen;
         protected Object[] kolomTypen;          // bevat een object van dezelfde class als die kolom
         protected int newRowsIndex;               // houd bij vanaf welke rij niewe regels zijn toegevoegd ivm het opslaan in de db
         protected int[]primecolumns;          //houd bij welke kolommen ingevuld moeten worden voordat de volgende regel getoond wordt (default= kolom 1)
         public EditableTableModel()
              keep = new ArrayList();               //visible
              changed=new ArrayList();               // not visisble
              primecolumns=new int[0];
              DATA=new ArrayList[0];
              kolomNamen =new String[0];
              kolomTypen=new Object[0];
              emptyLineIndex=-1;
              newRowsIndex=-1;
         * the constructor, creates a new EditableTableModel
         *@param data          an array of ArrayLists each arrayList contains the values of an entire column
         *@param names          an array containg the names of the columns
         *@param type          an array containing Objects which correspond to the objects in the columns
         public EditableTableModel(ArrayList[] data, String[] names, Object[] type)
              keep = new ArrayList();               //visible
              changed=new ArrayList();               // not visisble     
              primecolumns=new int[1];
              primecolumns[0]=1;
              DATA=data;
              for(int i=0;i<getRowCount();i++)
                   keep.add(new Boolean(true));
                   changed.add(new Boolean(false));
              kolomNamen=names;
              kolomTypen=type;
              emptyLineIndex=getRowCount()-1;
              addNewLine();
              newRowsIndex=emptyLineIndex;               // nieuwe regels beginnen op de lege regel
              addTableModelListener(this);
         * @return the number of rows/records
         public int getRowCount()
              return DATA[0].size();
         *@return the number of columns
         public int getColumnCount()
              return DATA.length+1;
         * returns the object containing the value for this cell
         * indexes start at 0 (wheter or not to keep this row), but the actual data starts at 1
         *@param row          the row in which the cell resides
         *@param column     the column in which the cell resides
         *@return the value of the cell wrapped in the appropiate Object
         public Object getValueAt(int row, int column)
              if(column==0)
                   return keep.get(row);
              else
                   return DATA[column-1].get(row);
         * allows editing of an existing value
         *@param value          the new value, should be of the same Object Type as the existing one
         *@param row               the row nr of the cell
         *@param col               the column nr of the cell
         public void setValueAt(Object value, int row, int col)
              if(col==0)
                   keep.set(row,value);
              else
                   DATA[col-1].set(row,value);
                   changed.set(row, new Boolean(true));
              fireTableCellUpdated(row, col);
         * adds a new "empty" row after all the PrimeColums of the last row have been filled with an acceptable value
         *@see setPrimeColumns
         protected void addNewLine()
              try
                   for(int i=0;i<DATA.length;i++)
                        if(kolomTypen[i] instanceof Integer)
                             DATA.add(new Integer(-1));
                        else
                        if(kolomTypen[i] instanceof Boolean)
                             DATA[i].add(new Boolean(false));
                        else
                        if(kolomTypen[i] instanceof Long)
                             DATA[i].add(new Long(-1));          //displayed as "" by cellrenderer
                        else
                             DATA[i].add(kolomTypen[i].getClass().newInstance());          //nieuw object aanmaken van het type dat gespecificeerd is, Integers en Booleans moet een waarde meegegeven worden
                   keep.add(new Boolean(true));
                   changed.add(new Boolean(false));
                   emptyLineIndex++;
              catch(Exception e)
                   e.printStackTrace();
         public void tableChanged(TableModelEvent e)
              if(e.getFirstRow()==emptyLineIndex)//alleen als de emptyLine ge?dit wordt een regel toevoegen
                   boolean primesfilled=true;
                   for(int i=0;i<primecolumns.length;i++)
                        if(getValueAt(emptyLineIndex,primecolumns[i]).equals(null) || getValueAt(emptyLineIndex,primecolumns[i]).toString().equals("")|| getValueAt(emptyLineIndex,primecolumns[i]).toString().equals("-1"))
                             primesfilled=false;
                             break;
                   if(primesfilled)     //alleen als de primaire sleutel kolommen ingevuld zijn
                        addNewLine();
         * returns the Class type of the Objects representing the column type
         *@param c     the column nr
         public Class getColumnClass(int c)
              if(c==0)
                   return new Boolean(true).getClass();
              else
                   return kolomTypen[c-1].getClass();
         *@param rowIndex the index of the row
         *@param columnIndex     the index of the column
         *@return true if a cell is Editable,false otherwise (all cells are Editable)
         public boolean isCellEditable(int rowIndex, int columnIndex)
              return true;
         * returns the name of the column
         *@param column     the column index
         *@return a String containing the name of the column
         public String getColumnName(int column)
              if(column==0)
                   return "";
              else
                   return kolomNamen[column-1];
         *@return wheter or not 1 or rows is marked for deletion
         public boolean deletionNeeded()
              Boolean B;
              for(int i=0;i<emptyLineIndex;i++)
                   B=(Boolean)keep.get(i);
                   if(!B.booleanValue())
                        return true;
              return false;
         * Deletes all rows which are marked for deletion
         *@return the number of rows that have been deleted
         public int deleteMarkedRows()          // zou niets uit moeten maken of je eerst deleteMarkedRows() of isSavedToDB(true) aanroept
              int aantalRows=0;
              Boolean B;
              for(int i=0;i<emptyLineIndex;i++)
                   B=(Boolean)keep.get(i);
                   if(!B.booleanValue())
                        if(deleteRow(i))
                             aantalRows++;
                             i--;
              return aantalRows;
         * deletes a single row
         *@param row     the row index
         *@return     true if the row was deleted, false otherwise
         protected boolean deleteRow(int row)
              boolean result=false;
              if(row==emptyLineIndex)               // emptyline kan niet gedelete worden
                   return result;
              try
                   for(int j=0;j<DATA.length;j++)
                        DATA[j].remove(row);
                   changed.remove(row);
                   keep.remove(row);
                   emptyLineIndex--;
                   if(row < newRowsIndex)
                        newRowsIndex--;
                   result=true;
              catch(Exception e)
                   e.printStackTrace();
              return result;
         * returns if the row has changed or not
         *@param row          the row index
         *@return true if 1 or more cells in this row had their value changed or if 1 or more rows were added, false otherwise
         public boolean hasChanged(int row)
              Boolean B=(Boolean)changed.get(row);
              return B.booleanValue();
         * Methode waarmee men kan bepalen of 1 van de originele waarden ook veranderd is.
         * Het geeft dus niet aan of er ook nieuwe rijen zijn toegevoegd.
         public boolean hasChanged()
              Boolean B;
              for(int i=0;i<newRowsIndex;i++)
                   B=(Boolean)changed.get(i);
                   if(B.booleanValue())
                        return true;
              return false;
         * if true it sets all flags indicating a change to false, else nothing
         *@param saved     boolean indicating all changes are now to be considerd to be the original values, or not
         public void isSavedToDB(boolean saved)
              if(saved)
                   for(int i=0; i<changed.size();i++)
                        changed.set(i,new Boolean(false));
                   newRowsIndex=emptyLineIndex;
         * @return the row nr. at which newly added entrys begin, updated after isSavedToDB(true) is called
         public int getNewRowsIndex()
              return newRowsIndex;
         * allows the specification of certain columns that need to be filled in, if not a new row will not be made vissible
         *@param columns     an array containing the column indexes which must be set to a valid value
         public void setPrimeColumns(int[] columns)
              primecolumns=columns;
         * allows retrieval of the PrimeColumns
         *@return an arrayof int containing the column indexes
         public int[] getPrimeColumns()
              return primecolumns;
    Ok some of the comments are in dutch go ahead an blame me :(
    if you have any questions, just ask.
    i also have a TableModel which can use automatic numbering
    Oh numbers (currently only Integer and Long) are initiated wth a value of -1 if you want to display them as blank cells like i wanted to you modify a cellrenderer (or use mine)
    Mr Mean

  • Table model problem

    I have a Jpanel in that there are two Jtables iam using same Table model for both tables.
    when i entered text in one table and clik on second table the first table data showing in second table how to do this one

    vitta wrote:
    I have a Jpanel in that there are two Jtables iam using same Table model for both tables.and
    vitta wrote:
    i dont want to get the first table values reflected in the second tableIn all honesty how is the answer to this question not exceedingly obvious?

  • Editable Table Model

    Forgive me if this question has been asked before, but I was wondering if anyone else is experiencing problems with Matisse and Table Models?
    After years of building GUIs by hand, I have begun to experiment with Matisse. One of the simple forms I am building contains a couple of JTables; the data for each provided by an instance of a subclass of AbstractTableModel that I already use successfully in an existing application. Running the form sees the model(s) supplying the data correctly but I cannot edit anything. The isCellEditable() method has been overloaded to return true all of the time but it is simply never being called when the user interacts with the form.
    Does anyone know if there is an easy - obvious - solution to this that will leave me feeling silly but help no end? Thanks in advance.

    Hello Zadok and thanks for the reply.
    Yes, it would be easier but I have tried doing that and still experience the same problem. It seems as though the edits are not being posted through the the table model. Does anyone know if I have to explicitly implement editors for each cell? Is there a setting in the list of properties that I should be using - by the way, I have layed around with these options a bit to no effect.

  • Can I modify a table model outside of the event thread if it's not seen?

    I have a JTable that I use to display several table models (I'm extending DefaultTableModel); I switch between the models using JTable.setModel.
    If model A is active and currently being viewed, I of course make sure any updates are done using SwingUtilities.invokeLater().
    My question is: Can I modify an "inactive" table, say table B, without using invokeLater(), for example B.setValueAt() etc.

    Isn't a model connected to an instance by JTable.setModel()? (Or by passing the model as a parameter in new JTable()) Yea. I meant connected to a JTable's UI. Or more specifically, listeners are installed on the model.
    if data is changing and the user is not currently viewing that data, I want to change the table model in another threadI would argue that this is thread safe:
    1) When a table becomes 'inactive' (not showing in any way) then you set the model to some static empty one.
    table.setModel(EMPTY_MODEL);This should happen on the EventDispatchThread. Setting the model to the empty one will uninstall all the listeners on the actual model.
    2) Freely modify the table's actual model in another Thread.
    3) When the table is about to become 'active', then you set the model back to the original one.
    table.setModel(originalModel);This should happen on the EventDispatchThread. In particular, the other thread should execute it with an invoke later. That way, proper synchronization occurs and the EDT sees all the changes made to the original model.

  • Difference between table and table model

    From what I've understood till now, in a JTable, the table itself is actually only a "display area" while the actual data is located in the table model. Is this correct?
    Does this mean it is possible to delete rows and columns within the table itself without affecting the actual data in the table model?

    Hi,
    ok, I will try to answer your second question "is it possible to delete rows and columns in the table but not in the table model"?
    The table - lets say the table's view - reflects the data of the data model only, if you fire the correct notification messages via the TableModelListener interface - JTable itself is a TableModelListener and updates its display accordingly to these messages - it never holds data by itself - if something is to be redrawn in the view, JTable ask the model via getValueAt(...) for the data and renders it using one of the cellrenderers delivered by the column of the column model resp. one of the registered default renderers.
    Now to your question - you can't delete a row in the tables view, without any change in the table model, as so the data isn't hold by the table's view, it is only held by the table model. But the other way round, it is possible - often accidentially - you can change the data in the table model and forget to fire a notification message for it via the TableModelListener interface - in this case, JTable will not update its view - and the table may look strange, if parts of its view is hidden by other applications and afterwards redrawn, when this application closes. Only the parts, that were hidden, will be redrawn - and this is done with the new data. So, keep track of always sending the correct notification message with every change you make in the table model, so that JTable is able to keep its view up to date.
    Hope this helps
    greetings Marsian

  • Use ComboBox TableCellEditor  - values are not saved to the table model

    Hi,
    I got a combobox cell editor that uses to edit one of the columns.
    And i got an ok button that uses to collect the data from the table and save it to the db.
    In case i started editing of a cell and the editor is still displayed- if i will click on the button the data that will be colected from the table model will not contained the updated value in the cell editor.
    In this case the user think his changes were saved but the last updated field is not updated.
    Is this a bug i got in the cell editor or this is the normal behaviour?
    Can it be fixed? (So that if the cell is in the middle of editing the value that will be saved is the last value that was selected).
    public class PriorityCellEditor extends StandardComboBox implements TableCellEditor {
        private boolean isEditMode=false;
         * A list of eventlisteners to call when an event is fired
        private EventListenerList listenerList = new EventListenerList();
         * the table model
        public StbAreaClusterPriorityCellEditor(boolean isEditMode) {
            super(StbAreaMapper.clustersPriorities);
            setEditMode(isEditMode);
            setEditable(false);
            this.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            setAlignmentX(Component.LEFT_ALIGNMENT);
        public boolean isEditMode() {
            return isEditMode;
        public void setEditMode(boolean editMode) {
            isEditMode = editMode;
            setEnabled(editMode);
        public Component getTableCellEditorComponent(JTable table, Object value,boolean isSelecte, int row, int column) {
            int selectedIndex;
            if (isSelecte) {
                setForeground(table.getSelectionForeground());
                setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(table.getBackground());
            if(value instanceof String){
                selectedIndex=StbAreaMapper.mapGuiPriorityDescToGuiCode((String)value);
                setSelectedIndex(selectedIndex);
            return this;
        public void cancelCellEditing() {
            fireEditingCanceled();
        public Object getCellEditorValue() {
            return getSelectedItem();
        public boolean isCellEditable(EventObject anEvent) {
            return isEditMode;
        public boolean shouldSelectCell(EventObject anEvent) {
            return false;
        public boolean stopCellEditing() {
            fireEditingStopped();
            return true;
         * Adds a new cellEditorListener to this cellEditor
        public void addCellEditorListener(CellEditorListener l) {
            listenerList.add(CellEditorListener.class, l);
         * Removes a cellEditorListener from this cellEditor
        public void removeCellEditorListener(CellEditorListener l) {
            listenerList.remove(CellEditorListener.class, l);
         * Notify all listeners that have registered interest for notification on
         * this event type.
         * @see javax.swing.event.EventListenerList
        protected void fireEditingStopped() {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length - 2; i >= 0; i -= 2) {
                if (listeners[i] == CellEditorListener.class) {
                    ((CellEditorListener) listeners[i + 1]).editingStopped(
                            new ChangeEvent(this));
         * Notify all listeners that have registered interest for notification on
         * this event type.
         * @see javax.swing.event.EventListenerList
        protected void fireEditingCanceled() {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying those that are interested in this event
            for (int i = listeners.length - 2; i >= 0; i -= 2) {
                if (listeners[i] == CellEditorListener.class) {
                    ((CellEditorListener) listeners[i + 1]).editingCanceled(new ChangeEvent(this));
    }

    Try this
    yourTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

  • Adding data to a table model at run time

    hiii
    i want to add data to the table model at runtime.
    i have used TableModel.My code looks like this
    public class CaptureTableModel extends AbstractTableModel {
         private String[] columnNames = { "No", "Source", "Destination", "Protocol",
                   "Flags" };
         private TCPPacket tcpPacket;
         private List data;
         private static int counter = 0;
         private int columnCount = columnNames.length;
         public CaptureTableModel(){}
         public CaptureTableModel(TCPPacket tcp) {
              try{
              tcpPacket=tcp;
              counter++;
              byte[] tcpdata = tcpPacket.getData();
              String srcHost = tcpPacket.getSourceAddress();
              String dstHost = tcpPacket.getDestinationAddress();
              String tcpPacketData = new String(tcpdata, "ISO-8859-1");
              if (tcpPacketData == null)
                   tcpPacketData = "";
              int protocol = tcpPacket.getProtocol();
              String proto = null;
              if (protocol == 6)
                   proto = "TCP";
              long sequenceNumber = tcpPacket.getSequenceNumber();
              data = new ArrayList();
              String[] info = {
                        Integer.toString(counter),
                        srcHost,
                        dstHost,
                        proto,
                        "[ACK " + tcpPacket.isAck() + " ; FIN " + tcpPacket.isFin()
                                  + " ; PUSH " + tcpPacket.isPsh() + " ; RESET "
                                  + tcpPacket.isRst() + " ; SYN " + tcpPacket.isSyn()
                                  + " ; URGENT " + tcpPacket.isUrg() };
              data.add(info);
         } catch (Exception e) {
              e.printStackTrace();//return null;
         public int getRowCount() {
              return counter;
         public int getColumnCount() {
              return columnCount;
         public String getColumnName(int column) {
              return columnNames[column];
         public Object getValueAt(int rowIndex, int columnIndex) {
              System.out.println("the value in getValueAt"+((Object[])data.get(rowIndex))[columnIndex]);
              return ((Object[])data.get(columnIndex))[rowIndex];
              //return null;
    the method getValueAt is not bieng called..where am i going wrong.
    can anyone help me??

    Use the "code" formatting tags when posting code so the code retains its original formatting.
    i want to add data to the table model at runtime.Use the DefaultTableModel it supports dynamic methods like addRow(...), removeRow().

  • Copyig Data from a TABLE MODEL (TABLE) TO A FILE

    Hi guys,
    I wont to copy data from a Default Table Model to a File can someone write a pease of code that will do that for me.
    DefaultTableModel model = new DefaultTableModel();
    JTable table;
    public basic()
              super();
                  model.addColumn("Full Name");
                  model.addColumn("House No");
                  model.addColumn("Address");
                  model.addColumn("Town/County");
                  model.addColumn("Postcode");
                  model.addColumn("Telephone Number");
                  model.addColumn("Email Address");             
                  String[] socrates = { "Example", "33", "York RD", "Poole", "BH18 9RE", "01202776655", "[email protected]" };
                  model.addRow(socrates);
              /**This is the main setup for the Address Book
              *This has the main settings for the size, title
              *And main features of the Address book.
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setSize(new Dimension(800, 600));
              this.setTitle("Large Print Address Book");
              this.setLayout(new FlowLayout ());
              //Main Application Parts
              JLabel welcome = new JLabel("Welcome to Thomas's Address Book v2.0.1");
              welcome.setFont(arial20);
              this.add(welcome);
              //Menu Bar
              JMenuBar mb = new JMenuBar();
              this.setJMenuBar(mb);
              //Table
              table = new JTable(model);
              this.add(table);
              JMenu fm = new JMenu("File");
              fm.setFont(arial20);
              mb.add(fm);
              //Menu Items          
              JMenuItem Add = new JMenuItem("Add Record");
              Add.setFont(arial20);
              Add.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e) 
                        addw a = new addw();                    
              fm.add(Add);
              //Import from a file
              JMenuItem inp = new JMenuItem("Import Records");
              inp.setFont(arial20);
              inp.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e) 
                        //Opens Import Window.
                        inportw i = new inportw();                    
              fm.add(inp);
              JMenuItem quit = new JMenuItem("Exit");
              quit.setFont(arial20);
              fm.add(quit);
              quit.addActionListener(this);
    class inportw extends JFrame
              //*Add Window Properties and Settings
              public inportw ()
                   this.setSize(new Dimension(400, 150));
                   this.setTitle("Inport Records");
                   this.setLayout(new FlowLayout ());
                   this.setVisible(true);
                   //Nmae
                   JLabel error_note = new JLabel("Error Here - Need to make table final!?");
                   error_note.setFont(arial20);
                   this.add(error_note);
                   //Add Button
                   JButton binport = new JButton("Inport");
                   binport.addActionListener(new ActionListener()
                        public void actionPerformed(ActionEvent e) 
                             ArrayList data = new ArrayList();          
                   this.add(binport);
         public void actionPerformed(ActionEvent e)
              System.out.println("Application Exit");
              System.exit(0);
         public static void main(String[] args)
              basic b = new basic();
              The information from the atable needs to go into a .txt file with each row on a new line. It also needs to be in the inport/export window that is in a class on its own when someone clicks export.
    A complete peace of code would be helpfull that would do this for me. Thankyou guys.

    Rite then,
    In answer to both post yes i have done my own homework if thats what you wont to call it.
    And to the second post yes i have put in a File to export to. the code has not be pasted on my origanal post.
    //Export Button - Export Window
                   JButton bexport = new JButton("Export (BUAB)");
                   bexport.addActionListener(new ActionListener()
                        public void actionPerformed(ActionEvent e) 
                             System.out.println("Export Pressed ");
                             try
                                 FileWriter file = new FileWriter("AddressData.txt");
                                BufferedWriter out = new BufferedWriter(file);
                                 out.write("AddressBook data File");
                                out.close();
                             catch (Exception ei)
                             System.err.println("Error: " + ei.getMessage());
                   this.add(bexport);This is the export button,
    I think the code for the table model should be something like this:
    I wont to do something like this
    model.getModel().getValueAt(0, 0);
    Arrylist data = new arrylist();
    try
                                 FileWriter ffile = new FileWriter("AddressData.txt");
                                BufferedWriter out = new BufferedWriter(file);
                                 out.write(data);
                                out.close();
                             catch (Exception ei)
                             System.err.println("Error: " + ei.getMessage());
                                 }          Im not 100% sure how to get the information from the model into the arrylist, though a loop.
    If there is a section of a webpage that may help could someone please post it for me.
    Unfortunatly for me Im visualy impaired and find some of this hard. I learn though looking at examples and creating my own programs that do something similar.
    If no one wonts to help then that fine with me !

  • JTable column headers not displaying using custom table model

    Hi,
    I'm attempting to use a custom table model (by extending AbstractTableModel) to display the contents of a data set in a JTable. The table is displaying the data itself correctly but there are no column headers appearing. I have overridden getColumnName of the table model to return the correct header and have tried playing with the ColumnModel for the table but have not been able to get the headers to display (at all).
    Any ideas?
    Cheers

    Class PublicationTableModel:
    public class PublicationTableModel extends AbstractTableModel
        PublicationManager pubManager;
        /** Creates a new instance of PublicationTableModel */
        public PublicationTableModel(PublicationManager pm)
            super();
            pubManager = pm;
        public int getColumnCount()
            return GUISettings.getDisplayedFieldCount();
        public int getRowCount()
            return pubManager.getPublicationCount();
        public Class getColumnClass(int columnIndex)
            Object o = getValueAt(0, columnIndex);
            if (o != null) return o.getClass();
            return (new String()).getClass();
        public String getColumnName(int columnIndex)
            System.out.println("asked for column name "+columnIndex+" --> "+GUISettings.getColumnName(columnIndex));
            return GUISettings.getColumnName(columnIndex);
        public Publication getPublicationAt(int rowIndex)
            return pubManager.getPublicationAt(rowIndex);
        public Object getValueAt(int rowIndex, int columnIndex)
            Publication pub = (Publication)pubManager.getPublicationAt(rowIndex);
            String columnName = getColumnName(columnIndex);
            if (columnName.equals("Address"))
                if (pub instanceof Address) return ((Address)pub).getAddress();
                else return null;
            else if (columnName.equals("Annotation"))
                if (pub instanceof Annotation) return ((Annotation)pub).getAnnotation();
                else return null;
            etc
           else if (columnName.equals("Title"))
                return pub.getTitle();
            else if (columnName.equals("Key"))
                return pub.getKey();
            return null;
        public boolean isCellEditable(int rowIndex, int colIndex)
            return false;
        public void setValueAt(Object vValue, int rowIndex, int colIndex)
        }Class GUISettings:
    public class GUISettings {
        private static Vector fields = new Vector();
        private static Vector classes = new Vector();
        /** Creates a new instance of GUISettings */
        public GUISettings() {
        public static void setFields(Vector f)
            fields=f;
        public static int getDisplayedFieldCount()
            return fields.size();
        public static String getColumnName(int columnIndex)
            return (String)fields.elementAt(columnIndex);
        public static Vector getFields()
            return fields;
    }GUISettings.setFields has been called before table is displayed.
    Cheers,
    garsher

  • Transfer Data from a JTable to the table model

    Hi
    I' looking for a simple method to transfer the last user input in a table to the table model.
    For example:
    In a Dialog the user insert in a JTable a few values and leaves with OK. But the last input is not saved in the model. It is just saved after selecting a new field in the JTable before leaving the Dialog.
    Is there a call to transfer all input to the model?
    Thanks
    Guido

    class MyJTable extends JTable (
    public boolean validateInput() {
    if(isEditing()) {
    return cellEditor.stopCellEditing();
    return true;
    Call this method whenever you want the input value to be stored in the table model. The return value can be false if the input isn't valid, this will depend on the cell editor.
    The idea is:
    Ask if the table has an editor activated. (isEditing())
    If so, request the editor to store the value in the model.
    I haven't prouved the code, sorry, but I hope you get the idea and helps.

  • How can I add an adornment to a table model?

    Hi
    - Is it possible to add an adornment to a table model?
    -  If yes how can I do that? Interface? Sample?
    Thanks for any hint
    Hans

    Hi,
    How can I add an attribute to a node of a DOM
    Document?
    I want to add attribute Maximum="6" for all Grade node
    as <Grade Maximum="6">.
    Grade is a third level node in my document.
    ThanksGet the father of "Grade" elements as an element. Then get all elements named "Grade", and for each one set attribute "Maximum" with value "6". If you read api documentation you will know which methods to use.
    But for helping you in getting the "Grade" parent.
    1) get the root element of the Dom Doc
    2)get the father of the "Grade" father: getElementsBytagName("his name") -> it will return a Node List get the first element casting as Element if there's only one, or elese if not case
    3)the same method in 2 get the "Grade" father
    4)getElementByTagName("Grade") over the "Grade" father -> for each "grade" element on nodelist do whatever you need
    i hope u understood...

  • Problem with Table Model Listener

    I hava a JTable with three columns and dynamic number of rows. The first column has a text. Second column has check box and each third column has three radio buttons. I am using the table model listener to fetch the row and column which the user clicked. here is the code
    public void tableChanged(TableModelEvent e)
    row = e.getFirstRow();
    column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object value = model.getValueAt(row, column);
    System.err.println("Value: "<em>value.toString()</em>" Row: "<em>row</em>" Column: "+column);
    attendanceModel.setHolidays(row, value.toString());
    }Here is the problem
    {color:#ff0000}Case 1{color}: When I click the first radio button in first row and third column it works and the output of print statement is
    *{color:#993300}Value:0 Row:0 Column:2{color}*
    {color:#ff0000}Case 2{color}: Next I clicked the first radio button in second row and third column the method is not called nothing is printed
    {color:#ff0000}Case 3{color}: Now I clicked the first radio button in third row and thrid column, the method is called and the output of print statement is
    {color:#993300}*Value:0 Row:1 Column:2*{color} ; but the actual value of row should be 2*. Here it is showing the row and column of the previously selected item.
    But in {color:#ff0000}case 2{color} instead of first radio button if I selected the second radio button the print statement will print the correct value i.e
    {color:#993300}*Value:1 Row:1 Column:2*{color}
    ie If I select different radio button in each row the print statement shows the correct value. But if in each row the same radio button is selected its not working properly. For first row it prints properly. If same radio button is selected in second row the method is not called. But from next row onwards the row value is showing the previously selected row as in {color:#ff0000}case 3{color}.
    But for the checkboxes in column 2 the same is working properly. Each column has only one check box. So when I select the check box in each row the row and column values are getting changed accordingly.
    Could some one help please?
    Thanks,
    Zach.

    To get better help sooner, post a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://mindprod.com/jgloss/sscce.html] that demonstrates the incorrect behaviour.
    db

Maybe you are looking for

  • How do I create multiple types of child nodes in ADF  Faces Tree Component

    Hi, I am trying to construct a tree using ADF Faces. The tree I am trying to develop should look something like: - Departments + Dept 10 + Dept 20 + Dept 30 + Dept 40 - Employees + SCOTT +ALLEN + BLAKE The nodes shown at the top level should serve as

  • After effects CC won't start in Mavericks 10.9.3

    I just reinstalled OS X and updated it. I didn't realize that the 10.9.3 update was out until I found this problem. Anyway after al the OS stuff I installed the CC programs I use but after effects doesn't start. I know that there are compatibility is

  • Drag and drop components

    hi folks, am using jdev 11.1.1.5.0 - adfbc. when am i wondering about drag and drop components in ADF 11g. i get some of the example. http://www.oracle.com/technetwork/developer-tools/adf/learnmore/60-table-drag-n-drop-sample-176981.pdf http://www.ba

  • Choose an entry in Search help and not in its input field

    Hi to all, In my application I have a field with a search help. I want that this field only can be modified using a search help and this field can't be modified directly writing in this field. Is similar to transaction se63 - Translation - Abap objec

  • Problems importing from Compact Flash cards shot on Canon 5D Mark ll

    On my first attempt at importing footage from the Canon 5D Mark ll, but I've not been able to do so. I'm using FCP 7 and I downloaded the Canon Log & Transfer plug-in. I followed the instructions on Canon's website exactly, but when I get to the stag