JTable and TableModelEvent: tableChanged(TableModelEvent) called twice

Hi,
This question has already been posted (http://forum.java.sun.com/thread.jsp?forum=257&thread=114517) but wasn't answered at that time so i decided to make another attempt.
How comes that tableChanged(TableModelEvent) is executed twice for each change?
I've tried to see if the two events could be differenciated by retrieving their properties using the avalaible methods: getType(), getColumn(), getLastRow() etc... but they both come with the same properties values... no easy way to "filter" them in tableChanged() so...
Is there a way to only have one of them cast for one change?
Maybe JTable or TableModel methods to override or sthg like this...
This is a blocking problem for the application we're writting. so, any hint or workaround greatly welcome :)
This one was short... if u need further informations, just post a request for them as a reply, i'll be glad to add details :)
regards,
Silvin

I actually just solved that very problem with my code, as I was reading your post.
remove the model.addTableModelListener(...) call from your code. This is implicitly handled by JTable when you specify model as the TableModel for your table. Adding it again causes it to receive the events twice.
Hope that helps!

Similar Messages

  • TreeSelectionListener  valueChanged() called twice on selecting TreeNode

    Hi All,
    This is a class which extends JTree class forms a Tree displaying employee information.Listener is written which should find the list of selected Employee nodes of tree component.
    The method valueChanged() of treeListener is getting called twice for every node selected. Please find the code.
    Is there any alternative to find the list of selected nodes when they are selected using mouse or shift key.
    Even I am facing this in case of row selection of JTable.The listener method is called twice. Could you please let me know your views and any tutorials or examples codes for handling such cases.
    public class TestingTreeModel extends JTree {
         //public vector myMOType;
         public TestingTreeModel() {
              super();
         public void setData(ArrayList testVOs) {
              // set the option of selecting multiple nodes
              this.getSelectionModel().setSelectionMode(
                   TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
              this.setRootVisible(false);
              setModel(rootTreeNode, testVOs);
              // DefaultTreeModel is used.
              this.setModel(new DefaultTreeModel(rootTreeNode));
              // Listener for selected nodes..
              MyTreeSelectionListener myTreeListener = new MyTreeSelectionListener();
              this.addTreeSelectionListener(myTreeListener);
    // which sets the data.
         public void setModel(DefaultMutableTreeNode rootNode, ArrayList empVOs) {
              if empVOs!= null && empVOs.size() > 0) {
                   Iterator empItr = empVOs.iterator();
                   while (neItr.hasNext()) {
                        Employee empVO = (Employee) empItr.next();
                        DefaultMutableTreeNode node =
                             new DefaultMutableTreeNode(empVO.getName());
                        rootNode.add(node);
    // Listener
         public class MyTreeSelectionListener implements TreeSelectionListener {
              public void valueChanged(TreeSelectionEvent evt) {
                   // Get all nodes whose selection status has changed     
                   System.err.println("Listener is called here check how many times");
                   getSelectedNodes(evt);
         private void getSelectedNodes(TreeSelectionEvent evt) {
              System.err.println("came inside getSelectedNodes");
              TreePath[] paths = evt.getPaths();
              // Iterate through all affected nodes
              System.err.println(" Length is " + paths.length);
              for (int i = 0; i < paths.length; i++) {
                   TreePath tp = paths;
                   Object[] o = tp.getPath();
                   for (int j = 0; j < o.length; j++) {
                        System.out.println(
                             "Class: " + o[j].getClass() + "; value: " + o[j]);
                        if (o[j] instanceof DefaultMutableTreeNode) {
                             Object uo = ((DefaultMutableTreeNode) o[j]).getUserObject();
                             if (uo != null) {
                                  System.out.println(
                                       "\tUser object class: "
                                            + uo.getClass()
                                            + "; value: "
                                            + uo);
         private ArrayList empIDList = new ArrayList();
         private DefaultMutableTreeNode rootTreeNode = null;
    Thanks in advance.

    Hi Arun,
    JDev version is Studio Edition Version 11.1.1.5.0.
    Yes, i do have value change listener on the CompanyName LOV. What is a parameter form? The LOV is defined on the page in the following way:
                                <af:selectOneChoice value="#{bindings.CompanyName.inputValue}"
                                                    required="#{bindings.CompanyName.hints.mandatory}"
                                                    shortDesc="#{bindings.CompanyName.hints.tooltip}"
                                                    id="soc1" autoSubmit="true"
                                                    unselectedLabel="--select--"
                                                    contentStyle="width:17em;"
                                                    binding="#{backingBeanScope.backing_Company.soc1}"
                                                    valueChangeListener="#{backingBeanScope.backing_Company.companyChangeListener}">
                                  <f:selectItems value="#{bindings.CompanyName.items}"
                                                 binding="#{backingBeanScope.backing_Company.si1}"
                                                 id="si1"/>
                                </af:selectOneChoice>

  • OnRequestStart is called twice?

    If I dont use an onRequest method in Application.cfc, I find
    that on every request, the onRequestStart and onRequestEnd methods
    are called twice. I used the following code in Application.cfc:
    Any clues on this unique behaviour?

    When I put the arguments and return types, the functions in
    the following Application.cfc did
    not run more than once.

  • ADF Faces: dialog framework calls  twice prepareModel and prepareRender

    Hi ,
    does anybody know why ADF Faces dialog framework calls twice prepareModel and prepareRender lifecycle methods . That's a really problem for me because i'm calling db procedures through backing beans methods which are attached on components properties.
    I cannot allow myself to cal the procedures more than once.
    Can somebody help me?
    Krasi

    Okay, although the servlet doesn't require to be run inside the JSF context, I added "/faces" to the URL simply because this would allow me to query the "postback" flag. In other words, I changed the invocation URL from "/jrrun" to "/faces/jrrun".
    In the servlet's "service()" method I put:
    logger.debug(">>>>>> isPostBack? " + AdfFacesContext.getCurrentInstance().isPostback());
    I also attached a JSF PhaseListener to the whole thing.
    Then I opened the parent page, I clicked on the button and the dialog appeared. The console output follows:
    07/01/19 21:37:05 ------------- start of phase RESTORE_VIEW 1
    07/01/19 21:37:05 ------------- end of phase RESTORE_VIEW 1
    07/01/19 21:37:05 ------------- start of phase RENDER_RESPONSE 6
    2007-01-19 21:37:05,156 - DEBUG - >>>>>> RunJasperReport: beginning
    2007-01-19 21:37:05,156 - DEBUG - >>>>>> isPostBack? false
    2007-01-19 21:37:05,156 - DEBUG - >>>>>> RunJasperReport: repPath=/reports/newRegByBusType_Report.jasper
    2007-01-19 21:37:07,047 - DEBUG - >>>>>> RunJasperReport: report output (PDF) was generated successfully. Its total size is 59596 bytes.
    2007-01-19 21:37:07,047 - DEBUG - >>>>>> RunJasperReport: done
    07/01/19 21:37:07 ------------- end of phase RENDER_RESPONSE 6
    07/01/19 21:37:09 ------------- start of phase RESTORE_VIEW 1
    07/01/19 21:37:09 ------------- end of phase RESTORE_VIEW 1
    07/01/19 21:37:09 ------------- start of phase RENDER_RESPONSE 6
    2007-01-19 21:37:09,625 - DEBUG - >>>>>> RunJasperReport: beginning
    2007-01-19 21:37:09,625 - DEBUG - >>>>>> isPostBack? false
    2007-01-19 21:37:09,625 - DEBUG - >>>>>> RunJasperReport: repPath=/reports/newRegByBusType_Report.jasper
    2007-01-19 21:37:09,672 - DEBUG - >>>>>> RunJasperReport: report output (PDF) was generated successfully. Its total size is 59596 bytes.
    2007-01-19 21:37:09,688 - DEBUG - >>>>>> RunJasperReport: done
    07/01/19 21:37:09 ------------- end of phase RENDER_RESPONSE 6
    By the way, partialSubmit="true" has the same effect as partialSubmit="false".
    I'm not sure I understand you correctly. Or perhaps you don't understand me correctly.
    I haven't got a problem with the parent page. I have a problem with the dialog page. It's executed twice. The RENDER_RESPONSE phase (as well as the RESTORE_VIEW phase) is executed twice.
    I want it to be executed only once. I don't want the servlet to be executed twice.
    Let me point out again that in the Embedded OC4J (inside JDeveloper) everything is okay. The servlet is executed only once. However, the same thing on OAS 10.1.3.1 runs twice.

  • I NEED HELP!! Been calling since the end of Nov and being charged for a Warranty device. The device was returned the next day!! Been calling twice a week.. NEED RESOLUTION

    I NEED HELP!! Been calling since the end of Nov and being charged for a Warranty device. The device was returned the next day!! Been calling twice a week.. I NEED HELP 6 TCC TICKETS HAVE BEEN OPENED - PROMISED CALLS BACK AND NEVER GET CALLS.
    About to cancel my account and move to AT&T
    TCC TICKETS:  (removed)
    I am trying here for the last resort. After this evening my account along with my business account will be cancelled. Total lines that Verizon will have lost will be 93 lines.
    PLEASE SOMEONE JUST HELP ME!!!!
    I already tweeted and facebook messaged Verizon. Your CS group has gone down hill over the last 3-6 months. I use to enjoy being a customer.
    >> Edited to comply with the Verizon Wireless Terms of Service <<

    not all the lines have ETF's. I have 30 tablets and the rest phones. The phones have ETFs and the tablets are all month to month.
    The total to move my account over is going to come out to about $8500.
    Rep has been trying to get my business for years.  I was always loyal to Verizon until this happened.

  • JTable and integers

    I have a tablemodel that holds the headers and the amount of rows and then inputted into a Jtable.what im trying to do is gather information in certain columns(ie integers) and add them up with the end result displaying the total at the end of the column.i have tried calling the column but i havent had luck so far.Ive also tried creating a 2d array instead of the tablemodel but no luck

    i cannot input anything into my JTable when ur code is put into it. I think its because the tablemodel is (headers,35) so there are no values to start with in each row.
    Ive tried alternating ur code to make it add floats in a column but still no luck.
    public void BS()
           String[] headers = new String[]{"Assets", "", "Liabilities", "", "Owner's Equity", ""};
            DefaultTableModel model = new DefaultTableModel(headers,35);
            model.addTableModelListener(this);
            bstable = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
                   //  The Cost is not editable
                   public boolean isCellEditable(int row, int column)
                        int modelColumn = convertColumnIndexToModel( column );
                        return (modelColumn == 3) ? false : true;
            bstable.getTableHeader().setReorderingAllowed(false);
            bsscrollpane = new JScrollPane(bstable);
            bsscrollpane.setViewportView(bstable);
        public void tableChanged(TableModelEvent e)
              System.out.println(e.getSource());
              if (e.getType() == TableModelEvent.UPDATE)
                   int row = e.getFirstRow();
                   int column = e.getColumn();
                   if (column == 1)
                        TableModel model = bstable.getModel();
                                    Float     assets = ((Float)model.getValueAt(row, 1)).floatValue();
                        Float value = new Float(assets);
                        model.setValueAt(value, row, 1);
         }I dont know if the calculate column will work. Do i have to loop it so it keeps on adding the rows in the 1st column.?

  • JTable  and Renderer

    Hello guru,
    I have a JTable in my application and i have defined a renderer for the first column of my
    JTable.
    This is the code for this renderer
    public class LabelRenderer extends JLabel implements TableCellRenderer
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column)
    return this;
    I will like to change the background color of the first column and only in the active row of my JTable or ideally set a picture in this column. is this possible?
    I think i have to write something in this event:
    table.getModel().addTableModelListener(new TableModelListener()
    public void tableChanged(TableModelEvent e)
    int row = e.getFirstRow();
    int column = e.getColumn();
    //something .......
    How can i do this ?
    thank you for your help

    Just to add onto that:
    1) the method call is setBackground(Color c). not setBackgroundColor.
    2) and you'll have to call setOpaque(true) also or the color won't show up. You can do this in your constructor.
    Here is some example code to do what you wan. The unimplemented methods at the end should be included in your renderer class. It speeds up renderering a lot. See the java api docs for the reasons if you are curious:
    public class DataRenderer extends JLabel implements TableCellRenderer {
    private Color selectionColor;
    private Color backColor;
    public DataRenderer () {
              setOpaque(true);
              setHorizontalAlignment(SwingConstants.RIGHT);     
              selectionColor=new Color(206,207,255);
              backColor = new Color(240,240,240);     
    public Component getTableCellRendererComponent(
    JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int col) {
              if (value==null) //it hasn't been set yet               
                   return null;     
         if(isSelected)
         setBackground(selectionColor);
         else
         setBackground(backColor);
         setText(value.toString());
    return this;
         public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue){
         protected void firePropertyChange(String propertyName, Object oldValue, Object newValue){
         public void repaint(long tm, int x, int y, int width, int height){
         public void repaint(Rectangle r){
         public void revalidate(){
         public void validate() {
    Good Luck!

  • JTable and Databases

    Hi all,
    I have two files excerpts from my Java application. I feel that in order for me to get understood so well, with regards to a problem that challenged me, I had to post these two files as you can see below. They are called ResultSetTableModel.java and DisplayQueryResults.java [which gets displayed in an internal frame].
    I have this code from ResultSetTableModel
    // ResultSetTableModel.java
    // A TableModel that supplies ResultSet data to a JTable.
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import javax.swing.table.AbstractTableModel;
    // ResultSet rows and columns are counted from 1 and JTable
    // rows and columns are counted from 0. When processing
    // ResultSet rows or columns for use in a JTable, it is
    // necessary to add 1 to the row or column number to manipulate
    // the appropriate ResultSet column (i.e., JTable column 0 is
    // ResultSet column 1 and JTable row 0 is ResultSet row 1).
    public class ResultSetTableModel extends AbstractTableModel
       private Connection connection;
       private Statement statement;
       private ResultSet resultSet;
       private ResultSetMetaData metaData;
       private int numberOfRows;
       // keep track of database connection status
       private boolean connectedToDatabase = false;
       // constructor initializes resultSet and obtains its meta data object;
       // determines number of rows
       public ResultSetTableModel(String driver, String url,
          String username, String password, String query)
          throws SQLException, ClassNotFoundException {        
          // load database driver class
          Class.forName(driver);
          // connect to database
          connection = DriverManager.getConnection(url, username, password);
          // create Statement to query database
          statement = connection.createStatement(
             ResultSet.TYPE_SCROLL_INSENSITIVE,
             ResultSet.CONCUR_READ_ONLY);
          // update database connection status
          connectedToDatabase = true;
          // set query and execute it
          setQuery(query);
       } // end constructor ResultSetTableModel
       // get class that represents column type
       public Class getColumnClass(int column) throws IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine Java class of column
          try {
             String className = metaData.getColumnClassName(column + 1);
             // return Class object that represents className
             return Class.forName(className);
          } // end try
          catch (Exception exception) {
             exception.printStackTrace();
          } // end catch
          //return Object.class; // if problems occur above, assume type Object
          return getValueAt(0, column).getClass(); // added January 25, 2008 in stead of the one above
       } // end method getColumnClass
       // get number of columns in ResultSet
       public int getColumnCount() throws IllegalStateException {  
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine number of columns
          try  {
             return metaData.getColumnCount();
          } // end try
          catch (SQLException sqlException) {
             sqlException.printStackTrace();
          } // end catch
          return 0; // if problems occur above, return 0 for number of columns
       } // end method getColumnCount
       // get name of a particular column in ResultSet
       public String getColumnName(int column) throws IllegalStateException {   
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine column name
          try {
             return metaData.getColumnName(column + 1); 
          } // end try
          catch (SQLException sqlException) {
             sqlException.printStackTrace();
          } // end catch
          return ""; // if problems, return empty string for column name
       } // end method getColumnName
       // return number of rows in ResultSet
       public int getRowCount() throws IllegalStateException {     
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          return numberOfRows;
       } // end method getRowCount
       // obtain value in particular row and column
       public Object getValueAt(int row, int column)
          throws IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // obtain a value at specified ResultSet row and column
          try {
             resultSet.absolute(row + 1);
             return resultSet.getObject(column + 1);
          } // end try
          catch ( SQLException sqlException ) {
             sqlException.printStackTrace();
          } // end catch
          return ""; // if problems, return empty string object
       } // end method getValueAt
        * Don't need to implement this method unless your table's
        * editable.
      public boolean isCellEditable(int row, int column) { // Added on January 25, 2008 6:51 A.M.
         //Note that the data/cell address is constant,
         //no matter where the cell appears onscreen.
         if (column < 2) {
            return false;
         } else {
            return true;
       // set new database query string
       public void setQuery(String query)
          throws SQLException, IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // specify query and execute it
          resultSet = statement.executeQuery(query);
          // obtain meta data for ResultSet
          metaData = resultSet.getMetaData();
          // determine number of rows in ResultSet
          resultSet.last();                   // move to last row
          numberOfRows = resultSet.getRow();  // get row number    
          // notify JTable that model has changed
          fireTableStructureChanged();
       } // end method setQuery
       // close Statement and Connection              
       public void disconnectFromDatabase() {             
          if (!connectedToDatabase)                 
             return;
          // close Statement and Connection           
          try {                                           
             statement.close();                       
             connection.close();                      
          } // end try                                
          catch (SQLException sqlException) {                                           
             sqlException.printStackTrace();          
          } // end catch                              
          finally { // update database connection status                                          
             connectedToDatabase = false;             
          } // end finally                            
       } // end method disconnectFromDatabase         
    }  // end class ResultSetTableModelThe DisplayQueryResults code follows:
    // DisplayQueryResults.java
    // Display the contents of the Authors table in the
    // Books database.
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.JTable;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.Box;
    import javax.swing.JInternalFrame;
    import java.util.*; // for the Bundle
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    import javax.swing.event.InternalFrameAdapter;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.*; // step 1
    import javax.swing.table.TableModel; // step 1
    public class DisplayQueryResults extends JInternalFrame implements TableModelListener { // step 2
       // JDBC driver, database URL, username and password
       ResourceBundle bundle = ResourceBundle.getBundle("Accounting");
       String JDBC_DRIVER = bundle.getString("Driver");
       String DATABASE_URL = bundle.getString("URL");
       String USERNAME = bundle.getString("User");
       String PASSWORD = bundle.getString("Password");
       String DEFAULT_QUERY = bundle.getString("Query");
       private ResultSetTableModel tableModel;
       private JTextArea queryArea;
       static final int xOffset = 0, yOffset = 200;
       // create ResultSetTableModel and GUI
       public DisplayQueryResults() {  
          super("Sales of the Day",
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  false);//iconifiable
          //...Create the GUI and put it in the window...
          //Set the window's location.
          setLocation(xOffset, yOffset);
          // create ResultSetTableModel and display database table
          try {
             // create TableModel for results of query SELECT * FROM authors
             tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
                USERNAME, PASSWORD, DEFAULT_QUERY);
             // set up JTextArea in which user types queries
             queryArea = new JTextArea(DEFAULT_QUERY, 1, 100);
             queryArea.setWrapStyleWord(true);
             queryArea.setLineWrap(true);
             JScrollPane scrollPane = new JScrollPane(queryArea,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
             // set up JButton for submitting queries
             JButton submitButton = new JButton("Submit Query");
             // create Box to manage placement of queryArea and
             // submitButton in GUI
             Box box = Box.createHorizontalBox();
             box.add(scrollPane);
             box.add(submitButton);
             // create JTable delegate for tableModel
             final JTable resultTable = new JTable(tableModel);
             resultTable.setFillsViewportHeight(true); // Makes the empty space heights white
             resultTable.setRowSelectionAllowed(true);
             resultTable.getModel().addTableModelListener(this); // step 3
             // place GUI components on content pane
             add(box, BorderLayout.NORTH);
             add(new JScrollPane(resultTable), BorderLayout.CENTER);
             // create event listener for submitButton
             submitButton.addActionListener(
                new ActionListener()
                   // pass query to table model
                   public void actionPerformed(ActionEvent event)
                      // perform a new query
                      try
                         tableModel.setQuery(queryArea.getText());
                      } // end try
                      catch ( SQLException sqlException)
                         JOptionPane.showMessageDialog(null,
                            sqlException.getMessage(), "Database error",
                            JOptionPane.ERROR_MESSAGE);
                         // try to recover from invalid user query
                         // by executing default query
                         try {
                            tableModel.setQuery(DEFAULT_QUERY);
                            queryArea.setText(DEFAULT_QUERY);
                         } // end try
                         catch (SQLException sqlException2) {
                            JOptionPane.showMessageDialog(null,
                               sqlException2.getMessage(), "Database error",
                               JOptionPane.ERROR_MESSAGE);
                            // ensure database connection is closed
                            tableModel.disconnectFromDatabase();
                            System.exit(1); // terminate application
                         } // end inner catch                  
                      } // end outer catch
                   } // end actionPerformed
                }  // end ActionListener inner class         
             ); // end call to addActionListener
             //...Then set the window size or call pack...
                setSize(750,300);
             setVisible(true); // display window 
          } // end try
          catch (ClassNotFoundException classNotFound) {
             JOptionPane.showMessageDialog(null,
                "MySQL driver not found", "Driver not found",
                JOptionPane.ERROR_MESSAGE);
             System.exit(1); // terminate application
          } // end catch
          catch (SQLException sqlException) {
             JOptionPane.showMessageDialog(null, sqlException.getMessage(),
                "Database error", JOptionPane.ERROR_MESSAGE);
             // ensure database connection is closed
             tableModel.disconnectFromDatabase();
             System.exit(1);   // terminate application
          } // end catch
          // dispose of window when user quits application (this overrides
          // the default of HIDE_ON_CLOSE)
          setDefaultCloseOperation(DISPOSE_ON_CLOSE);
          // ensure database connection is closed when user quits application
          addInternalFrameListener(
             new InternalFrameAdapter() {
                // disconnect from database and exit when window has closed
                public void windowClosed(WindowEvent event) {
                   tableModel.disconnectFromDatabase();
                   System.exit(0);
                } // end method windowClosed
             } // end WindowAdapter inner class
          ); // end call to addWindowListener
       } // end DisplayQueryResults constructor
       public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data");
       // execute application
       public static void main(String args[]) {
          new DisplayQueryResults();    
       } // end main
    } // end class DisplayQueryResultsMy problem:
    is in these lines:
    public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data"); // should output in the console
        }How do we notify java that a cell on a row has changed so that we can reflect the changes to the database. The current application shows that the data in cells are editable, but when we edit a cell and hit enter, data changes back to the previous data in that particular cell. And the data as well does not change its state: for example, if a data in the table has a value of boolean value false [checkbox unchecked], I can not modify the checkbox state to checked state. The tableChanged method does not get executed, and therefore, this is a serious error that I cant figure out.
    My question:
    What code should I write so that I will be able to notify java of the changed cell and how do we write the code that will reflect the changed values in a cell into the database?
    Edited by: Oliverbob on Jan 26, 2008 8:40 PM

    This maybe what you're looking for??
    http://developer.java.sun.com/developer/Books/swing2/chapter18-09.html

  • JTable and Database communication

    Hi all,
    I have two files excerpts from my Java application. I feel that in order for me to get understood so well, with regards to a problem that challenged me, I had to post these two files as you can see below. They are called ResultSetTableModel.java and DisplayQueryResults.java [which gets displayed in an internal frame].
    I have this code from ResultSetTableModel
    // ResultSetTableModel.java
    // A TableModel that supplies ResultSet data to a JTable.
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import javax.swing.table.AbstractTableModel;
    // ResultSet rows and columns are counted from 1 and JTable
    // rows and columns are counted from 0. When processing
    // ResultSet rows or columns for use in a JTable, it is
    // necessary to add 1 to the row or column number to manipulate
    // the appropriate ResultSet column (i.e., JTable column 0 is
    // ResultSet column 1 and JTable row 0 is ResultSet row 1).
    public class ResultSetTableModel extends AbstractTableModel
       private Connection connection;
       private Statement statement;
       private ResultSet resultSet;
       private ResultSetMetaData metaData;
       private int numberOfRows;
       // keep track of database connection status
       private boolean connectedToDatabase = false;
       // constructor initializes resultSet and obtains its meta data object;
       // determines number of rows
       public ResultSetTableModel(String driver, String url,
          String username, String password, String query)
          throws SQLException, ClassNotFoundException {        
          // load database driver class
          Class.forName(driver);
          // connect to database
          connection = DriverManager.getConnection(url, username, password);
          // create Statement to query database
          statement = connection.createStatement(
             ResultSet.TYPE_SCROLL_INSENSITIVE,
             ResultSet.CONCUR_READ_ONLY);
          // update database connection status
          connectedToDatabase = true;
          // set query and execute it
          setQuery(query);
       } // end constructor ResultSetTableModel
       // get class that represents column type
       public Class getColumnClass(int column) throws IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine Java class of column
          try {
             String className = metaData.getColumnClassName(column + 1);
             // return Class object that represents className
             return Class.forName(className);
          } // end try
          catch (Exception exception) {
             exception.printStackTrace();
          } // end catch
          //return Object.class; // if problems occur above, assume type Object
          return getValueAt(0, column).getClass(); // added January 25, 2008 in stead of the one above
       } // end method getColumnClass
       // get number of columns in ResultSet
       public int getColumnCount() throws IllegalStateException {  
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine number of columns
          try  {
             return metaData.getColumnCount();
          } // end try
          catch (SQLException sqlException) {
             sqlException.printStackTrace();
          } // end catch
          return 0; // if problems occur above, return 0 for number of columns
       } // end method getColumnCount
       // get name of a particular column in ResultSet
       public String getColumnName(int column) throws IllegalStateException {   
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine column name
          try {
             return metaData.getColumnName(column + 1); 
          } // end try
          catch (SQLException sqlException) {
             sqlException.printStackTrace();
          } // end catch
          return ""; // if problems, return empty string for column name
       } // end method getColumnName
       // return number of rows in ResultSet
       public int getRowCount() throws IllegalStateException {     
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          return numberOfRows;
       } // end method getRowCount
       // obtain value in particular row and column
       public Object getValueAt(int row, int column)
          throws IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // obtain a value at specified ResultSet row and column
          try {
             resultSet.absolute(row + 1);
             return resultSet.getObject(column + 1);
          } // end try
          catch ( SQLException sqlException ) {
             sqlException.printStackTrace();
          } // end catch
          return ""; // if problems, return empty string object
       } // end method getValueAt
        * Don't need to implement this method unless your table's
        * editable.
      public boolean isCellEditable(int row, int column) { // Added on January 25, 2008 6:51 A.M.
         //Note that the data/cell address is constant,
         //no matter where the cell appears onscreen.
         if (column < 2) {
            return false;
         } else {
            return true;
       // set new database query string
       public void setQuery(String query)
          throws SQLException, IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // specify query and execute it
          resultSet = statement.executeQuery(query);
          // obtain meta data for ResultSet
          metaData = resultSet.getMetaData();
          // determine number of rows in ResultSet
          resultSet.last();                   // move to last row
          numberOfRows = resultSet.getRow();  // get row number    
          // notify JTable that model has changed
          fireTableStructureChanged();
       } // end method setQuery
       // close Statement and Connection              
       public void disconnectFromDatabase() {             
          if (!connectedToDatabase)                 
             return;
          // close Statement and Connection           
          try {                                           
             statement.close();                       
             connection.close();                      
          } // end try                                
          catch (SQLException sqlException) {                                           
             sqlException.printStackTrace();          
          } // end catch                              
          finally { // update database connection status                                          
             connectedToDatabase = false;             
          } // end finally                            
       } // end method disconnectFromDatabase         
    }  // end class ResultSetTableModelThe DisplayQueryResults code follows:
    // DisplayQueryResults.java
    // Display the contents of the Authors table in the
    // Books database.
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.JTable;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.Box;
    import javax.swing.JInternalFrame;
    import java.util.*; // for the Bundle
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    import javax.swing.event.InternalFrameAdapter;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.*; // step 1
    import javax.swing.table.TableModel; // step 1
    public class DisplayQueryResults extends JInternalFrame implements TableModelListener { // step 2
       // JDBC driver, database URL, username and password
       ResourceBundle bundle = ResourceBundle.getBundle("Accounting");
       String JDBC_DRIVER = bundle.getString("Driver");
       String DATABASE_URL = bundle.getString("URL");
       String USERNAME = bundle.getString("User");
       String PASSWORD = bundle.getString("Password");
       String DEFAULT_QUERY = bundle.getString("Query");
       private ResultSetTableModel tableModel;
       private JTextArea queryArea;
       static final int xOffset = 0, yOffset = 200;
       // create ResultSetTableModel and GUI
       public DisplayQueryResults() {  
          super("Sales of the Day",
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  false);//iconifiable
          //...Create the GUI and put it in the window...
          //Set the window's location.
          setLocation(xOffset, yOffset);
          // create ResultSetTableModel and display database table
          try {
             // create TableModel for results of query SELECT * FROM authors
             tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
                USERNAME, PASSWORD, DEFAULT_QUERY);
             // set up JTextArea in which user types queries
             queryArea = new JTextArea(DEFAULT_QUERY, 1, 100);
             queryArea.setWrapStyleWord(true);
             queryArea.setLineWrap(true);
             JScrollPane scrollPane = new JScrollPane(queryArea,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
             // set up JButton for submitting queries
             JButton submitButton = new JButton("Submit Query");
             // create Box to manage placement of queryArea and
             // submitButton in GUI
             Box box = Box.createHorizontalBox();
             box.add(scrollPane);
             box.add(submitButton);
             // create JTable delegate for tableModel
             final JTable resultTable = new JTable(tableModel);
             resultTable.setFillsViewportHeight(true); // Makes the empty space heights white
             resultTable.setRowSelectionAllowed(true);
             resultTable.getModel().addTableModelListener(this); // step 3
             // place GUI components on content pane
             add(box, BorderLayout.NORTH);
             add(new JScrollPane(resultTable), BorderLayout.CENTER);
             // create event listener for submitButton
             submitButton.addActionListener(
                new ActionListener()
                   // pass query to table model
                   public void actionPerformed(ActionEvent event)
                      // perform a new query
                      try
                         tableModel.setQuery(queryArea.getText());
                      } // end try
                      catch ( SQLException sqlException)
                         JOptionPane.showMessageDialog(null,
                            sqlException.getMessage(), "Database error",
                            JOptionPane.ERROR_MESSAGE);
                         // try to recover from invalid user query
                         // by executing default query
                         try {
                            tableModel.setQuery(DEFAULT_QUERY);
                            queryArea.setText(DEFAULT_QUERY);
                         } // end try
                         catch (SQLException sqlException2) {
                            JOptionPane.showMessageDialog(null,
                               sqlException2.getMessage(), "Database error",
                               JOptionPane.ERROR_MESSAGE);
                            // ensure database connection is closed
                            tableModel.disconnectFromDatabase();
                            System.exit(1); // terminate application
                         } // end inner catch                  
                      } // end outer catch
                   } // end actionPerformed
                }  // end ActionListener inner class         
             ); // end call to addActionListener
             //...Then set the window size or call pack...
                setSize(750,300);
             setVisible(true); // display window 
          } // end try
          catch (ClassNotFoundException classNotFound) {
             JOptionPane.showMessageDialog(null,
                "MySQL driver not found", "Driver not found",
                JOptionPane.ERROR_MESSAGE);
             System.exit(1); // terminate application
          } // end catch
          catch (SQLException sqlException) {
             JOptionPane.showMessageDialog(null, sqlException.getMessage(),
                "Database error", JOptionPane.ERROR_MESSAGE);
             // ensure database connection is closed
             tableModel.disconnectFromDatabase();
             System.exit(1);   // terminate application
          } // end catch
          // dispose of window when user quits application (this overrides
          // the default of HIDE_ON_CLOSE)
          setDefaultCloseOperation(DISPOSE_ON_CLOSE);
          // ensure database connection is closed when user quits application
          addInternalFrameListener(
             new InternalFrameAdapter() {
                // disconnect from database and exit when window has closed
                public void windowClosed(WindowEvent event) {
                   tableModel.disconnectFromDatabase();
                   System.exit(0);
                } // end method windowClosed
             } // end WindowAdapter inner class
          ); // end call to addWindowListener
       } // end DisplayQueryResults constructor
       public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data");
       // execute application
       public static void main(String args[]) {
          new DisplayQueryResults();    
       } // end main
    } // end class DisplayQueryResultsMy problem:
    is in these lines:
    public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data"); // should output in the console
        }How do we notify java that a cell on a row has changed so that we can reflect the changes to the database. The current application shows that the data in cells are editable, but when we edit a cell and hit enter, data changes back to the previous data in that particular cell. And the data as well does not change its state: for example, if a data in the table has a value of boolean value false [checkbox unchecked], I can not modify the checkbox state to checked state. The tableChanged method does not get executed, and therefore, this is a serious error that I cant figure out.
    My question:
    What code should I write so that I will be able to notify java of the changed cell and how do we write the code that will reflect the changed values in a cell into the database?
    Edited by: Oliverbob on Jan 26, 2008 9:54 PM

    Why don't you check out the link shown below:
    http://www.aokabc.com
    and just follow the white rabbit!
    ;o)
    V.V.

  • Edit JTable and Send Info To DB!!!!!  Duke$$$$

    hi,
    I have an Applet that contains JTable.
    I am retriveing person information from DB to jTable...
    Once i click on the JTable i want to change the value in the JTable cell and click the Update button to update that info in db...
    Can someone please guide me on how this can be done...
    If possible if someone can post a simple code or post where i can get an example like this...
    Again Thanks for any help..
    Sam

    take a look at this code.
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class SimpleTableDemo extends JFrame implements TableModelListener {
    private boolean DEBUG = true;
    javax.swing.table.TableModel modela;
    public SimpleTableDemo() {
    super("SimpleTableDemo");
    Object[][] data = {
    {"Mary", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", "Andrews",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
    String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    modela = table.getModel();
    modela.addTableModelListener(this);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public void tableChanged(TableModelEvent e){
    int row = e.getFirstRow();
    int column = e.getColumn();
    Object firstname = modela.getValueAt(row, 0);
    Object lastname = modela.getValueAt(row, 1);
    Object sport = modela.getValueAt(row, 2);
    Object years = modela.getValueAt(row, 3);
    Object veg = modela.getValueAt(row, 4);
    System.out.println();
    System.out.println(firstname);
    System.out.println(lastname);
    System.out.println(sport);
    System.out.println(years);
    System.out.println(veg);
    System.out.println();
    public static void main(String[] args) {
    SimpleTableDemo frame = new SimpleTableDemo();
    frame.pack();
    frame.setVisible(true);
    hope this helps

  • JTable and storing up-dated in a file

    The first task is to save data entered in the JTable to a file.
    I could not do this as I could not access the updated model.
    I include the three files. At the moment the method tableChanged is stopping the init method loading because it sees this a table changed.
    Any help after a day slogging at this would be most appreciated.
    Yours Sincerely,
    Kieran A. Murray
    package tables;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.Vector;
    import javax.swing.table.*;
    public class PowerFrame extends JFrame
    private JFrame PowerFrame;
    private JTabbedPane PowerTabPane;
    private JMenuItem fMenuOpen = null;
    private JMenuItem fMenuSave = null;
    private JMenuItem fMenuClose = null;
    JavaFilter fJavaFilter = new JavaFilter ();
    File fFile = new File ("default.dat");
    private Object Vectorin;
    private Object v;
    public Vector q;
    private int count;
    private int xcount;
    private int qcount;
    private int ycount;
    private int pcount;
    private File file;
    BusbarRecords Busbar = new BusbarRecords();
    BusbarsUI ui = new BusbarsUI();
    public PowerFrame () {
         super("Begin at the Beginning");
         addWindowListener(new WindowAdapter()
         { public void windowClosing(WindowEvent e)
         { System.exit(0);
         PowerTabPane = new JTabbedPane(SwingConstants.RIGHT);
         PowerTabPane.setBackground(Color.blue);
         PowerTabPane.setForeground(Color.white);
         populatePowerTabbedPane();
         buildMenu();
         getContentPane().add(PowerTabPane);
    private void populatePowerTabbedPane()
         PowerTabPane.addTab("Busbars", null, new BusbarsUI(), "Data for Busbar");
    private void buildMenu()
         JMenuBar mb = new JMenuBar();
         JMenu menu = new JMenu("File");
         setJMenuBar (mb);
         setSize (400,400);
         JMenuItem openitem = new JMenuItem("Open");
         JMenuItem saveitem = new JMenuItem("Save");
         JMenuItem exititem = new JMenuItem("Exit");
         exititem.addActionListener(new ActionListener()
         public void actionPerformed(ActionEvent e)
         System.exit(0);
         openitem.addActionListener(new ActionListener()
         public void actionPerformed ( ActionEvent e ) {
              boolean status = false;
              status = openFile ();
              if (!status)
              JOptionPane.showMessageDialog (
              null,
              "Error opening file!", "File Save Error",
              JOptionPane.ERROR_MESSAGE);
         saveitem.addActionListener(new ActionListener()
         public void actionPerformed ( ActionEvent e ) {
              boolean status = false;
              status = saveFile ();
              if (!status)
              JOptionPane.showMessageDialog (
              null,
              "Error opening file!", "File Open Error",
              JOptionPane.ERROR_MESSAGE);
         menu.add(openitem);
         menu.add(saveitem);
         menu.add(exititem);
         mb.add(menu);
         setJMenuBar(mb);
         * Use a JFileChooser in Open mode to select files
         * to open. Use a filter for FileFilter subclass to select
         * for *.java files. If a file is selected then read the
         * file and place the string into the textarea.
         boolean openFile () {
         JFileChooser fc = new JFileChooser ();
         fc.setDialogTitle ("Open File");
         // Choose only files, not directories
         fc.setFileSelectionMode ( JFileChooser.FILES_ONLY);
         // Start in current directory
         fc.setCurrentDirectory (new File ("."));
         // Set filter for Java source files.
         fc.setFileFilter (fJavaFilter);
         // Now open chooser
         int result = fc.showOpenDialog (this);
         if (result == JFileChooser.CANCEL_OPTION) {
         return true;
         } else if (result == JFileChooser.APPROVE_OPTION) {
         fFile = fc.getSelectedFile ();
                   // Invoke the readFile method in this class
         q = (Vector) readFile (fFile);
              System.out.println(q.elementAt(1));
         /*ui.readFileIntoJTable(q);*/
         } else {
         return false;
         return true;
         } // openFile
         boolean saveFile () {
              File file = null;
              JFileChooser fc = new JFileChooser ();
              // Start in current directory
              fc.setCurrentDirectory (new File ("."));
              // Set filter for Java source files.
              fc.setFileFilter (fJavaFilter);
              // Set to a default name for save.
              fc.setSelectedFile (fFile);
              // Open chooser dialog
              int result = fc.showSaveDialog (this);
              if (result == JFileChooser.CANCEL_OPTION) {
              return true;
              } else if (result == JFileChooser.APPROVE_OPTION) {
              fFile = fc.getSelectedFile ();
              if (fFile.exists ()) {
              int response = JOptionPane.showConfirmDialog (null,
              "Overwrite existing file?","Confirm Overwrite",
              JOptionPane.OK_CANCEL_OPTION,
              JOptionPane.QUESTION_MESSAGE);
              if (response == JOptionPane.CANCEL_OPTION) return false;
              return ui.getJTableFields(fFile);
              else{
              return false;
              } // saveFile
         public Object readFile (File file) {
              try{
                   FileInputStream fis = new FileInputStream(file);
                   ObjectInputStream ois = new ObjectInputStream(fis);
                   v = ois.readObject();
                   fis.close();
              catch(Exception e){
                   System.err.println("Exception:" + e.getMessage());
              return (v);
    public static void main(String[] args)
         PowerFrame PF = new PowerFrame();
         PF.pack();
         PF.setSize(765,690);
         PF.setBackground(Color.white);
         PF.setVisible(true);
    package tables;
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    public class BusbarsUI extends JPanel implements TableModelListener {
         private boolean DEBUG = true;
    private int xcount;
    private int ycount;
    private int pcount;
    private int qcount;
    private int y;
    private TableModel newmodel;
    JTable table;
         BusbarRecords Busbar=new BusbarRecords();
    public BusbarsUI() {
         init();
    public void init(){
         DefaultTableModel model = new DefaultTableModel();
         model.addTableModelListener( this );
         JTable table = new JTable(model);
         setLayout(new BorderLayout());
         setBackground(Color.white);
         Vector p = Busbar.setJTableFields();
    String[] s = initializevector();
    System.out.println(p.size());
         for (xcount=1; xcount <= Busbar.columnNames.length;xcount++)
              model.addColumn(Busbar.columnNames [xcount-1]);
         for (qcount=1; qcount <= 5; qcount++)
         model.addRow(s);
              pcount=1;
         while (pcount < (p.size()-1))
              for (ycount=1; ycount <= p.size()/5; ycount++)
                   for (xcount=1; xcount <= Busbar.columnNames.length;xcount++)
                        model.setValueAt(p.elementAt(pcount-1), ycount-1, xcount-1);
                        pcount++;
         model.addRow(new Object[]{""});
    for (pcount=0; pcount <= p.size()-1; pcount++)
         System.out.println(p.elementAt(pcount));
    table.setPreferredScrollableViewportSize(table.getPreferredSize());
    JScrollPane scrollPane = new JScrollPane(table);
    add(scrollPane, BorderLayout.CENTER);
    public void tableChanged(TableModelEvent e)
              System.out.println(e.getSource());
              if (e.getType() == TableModelEvent.UPDATE)
                   int row = e.getFirstRow();
                   int column = e.getColumn();
                        TableModel model = table.getModel();
                        model.getValueAt(row,column);
                        Vector g = new Vector();
                        for(int i=0; i < model.getRowCount();i++){
                             for(int j=0;j < model.getColumnCount();j++){
                                  g.addElement(model.getValueAt(i,j));
    private void stopEditing() {
         if (table.getCellEditor() != null)
         table.getCellEditor().stopCellEditing();
    private String[] initializevector()
         String[] v = new String[5];
         for (int i=0; i<5;i++)
              v="";
         return v;
         /* public JTable update()
              for (xcount=1; xcount <= Busbar.columnNames.length;xcount++)
                   for (qcount=1; qcount <= 5; qcount++)
                        System.out.println(model.getValueAt(ycount-1, xcount-1));
              JTable table = new JTable(model);
              return table;
    /* public JTable readFileIntoJTable(Object q)*/
    public boolean getJTableFields(File file)
         Vector g = new Vector();
         stopEditing();
         /*for(int i=0; i < model.getRowCount();i++){
              for(int j=0;j < model.getColumnCount();j++){
                   g.addElement(model.getValueAt(i,j));
         int numRows=model.getRowCount();
         int numCols= model.getColumnCount();
    System.out.println("Value of data: ");
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + table.getValueAt(i, j));
    System.out.println();
    System.out.println("--------------------------");*/
    try
              FileOutputStream fos = new FileOutputStream(file);
              ObjectOutputStream object = new ObjectOutputStream(fos);
              object.writeObject(g);
              object.flush();
              object.close();
         catch(Exception ex)
              System.out.println("Exception:" + ex);
              return false;
              return true;
    package tables;
    import java.io.*;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;
    import java.util.Vector;
    public class BusbarRecords implements Serializable
    private String firstName, lastName, sport;
    private int years;
    private boolean vegetarian;
    private int xcount;
    private int ycount;
    private int pcount;
    private int y;
    private PowerFrame PR;
    File file;
    String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    Object [][] data = {
    {"Mary", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", "Andrews",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
         public Vector setJTableFields(){
              Vector p = new Vector();
         for (ycount =1; ycount <=5; ycount++)
              for(xcount=1; xcount <= columnNames.length; xcount++)
                   p.add("one");
         return p;
    package tables;
    import javax.swing.*;
    import java.io.*;
    /** Filter to work with JFileChooser to select java file types. **/
    public class JavaFilter extends javax.swing.filechooser.FileFilter
    public boolean accept (File f) {
    return f.getName ().toLowerCase ().endsWith (".java")
    || f.isDirectory ();
    public String getDescription () {
    return "Java files (*.java)";
    } // class JavaFilter

    brilliant thanks Dr Clap thats just what i was looking for - ive been wasting time searching thru thr ROME and Informa API's for a way of doing this before realising that i just need to write the URL's into a file and the read from them !!

  • JTable and Graphics

    Hi,
    I have a graphic with the axis x and y. With MouseListener, i get the mouse's coordinates. When i do 'clik' draw a point and now i want the point's coordinates in a table (JTable).
    I need some ideas for make this.
    Thanks for the help.

    OK, thanks.
    The point is that I want to chage a row of my table: X in (1, 1) and Y (1,2).
    x and y are the mouse's coordinates in the graphic when i make "click".
    Now i have a class "MyClass" and implements TableModelListener and i have wrotten the next listener:
    intable.myModel1.addTableModelListener(this);intable: class's object with the table (JTable).
    myModel: the table's model.
    public void tableChanged(TableModelEvent e)
            Double x = new Double(xCursor);
            Double y = new Double(yCursor);
            int row = e.getFirstRow();
            int column = e.getColumn();
            intable.myModel1.setValueAt(x.toString(), row, column);
            intable.myModel1.setValueAt(y.toString(), row, column+1);
         }I have wrotten this to edit the cell but doesnt work :(
    In my model setValueAt haves this form:
    public void setValueAt(Object value, int row, int col) {
                      filaDatos[row][col] = value;
                              fireTableCellUpdated(row, col);
                 }Some idea?
    Thanks and sorry for my english.

  • Is this a Bug?: FocusListener called twice

    Hey all,
    Im having this problem since realease 1.4.2_04.
    Folks, try this code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class FocusTest {
        public static void main(String[] args) {
            JFrame frame  = new JFrame("Focus test");
            final JTextField field1 = new JTextField("Test1");
            final JTextField field2 = new JTextField("Test2");
            field1.addFocusListener(new FocusAdapter(){
                public void focusGained(FocusEvent e){}
                public void focusLost(FocusEvent e){
                    if( !e.isTemporary() ){
                        System.out.println("ID: " + e.getID());
                        JOptionPane.showMessageDialog(null, "Focus lost in 1");
                        field1.requestFocus();
            frame.getContentPane().add(field1, BorderLayout.WEST);
            frame.getContentPane().add(field2, BorderLayout.CENTER);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setBounds(0,0,200,300);
            frame.show();
    } The problem is: when TF1 looses its focus, and is validated, then i force the focus to keep on TF1 by calling TF1.requestFocus(), somehow the event focusLsot is called twice for my TF.
    If i do not requestFocus() it work but I must force the focus on TF1.
    Im going nuts. Does anyonw apear to have this problems?? In old realeses, the same code work perfect. until 1.4.2 beta.
    Tks
    Bruno

    Hello all!
    I found out that somehow JDialog with requestfocus after, fires twice the lostFocus event. I dont know why. I opened a bug report so they can figure it out why is happaning.
    Tks folks!
    Bruno

  • HT1212 my iphone 5's screen blacks out every now and then. the phone is turned on but the screen is black and i can receive calls. what is wrong with my phone

    my iphone 5's screen blacks out every now and then. the phone is turned on but the screen is black and i can receive calls. what is wrong with my phone?

    I have to believe this has something to do with iOS 7 issues. I have taken my screen blacked out 5s twice to the Genius Bar and the found a bunch of system apps had crashed.  So if this is the case, is iOS7 the problem?

  • 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

Maybe you are looking for

  • Strange Database issues while trying to create new user through EM...

    I'm attempting to configure my local Oracle 11g database in order to create a Content Server user in order to setup a Fatwire installation. I'm getting some strange issues with my database that I was hoping maybe someone could help me out with. The g

  • IPod Nano troubles, please help

    I'll try to explain this problem to the best of my ability, this has been an ongoing problem since my sister got her iPod Nano: Me and my sister both got iPods for Christmas, her a Nano and myself a Video, now this isn't about me, my iPod works with

  • Dynamic file name in case of .txt output files

    Hi all, I have a query related to dynamic file name scenario. In case of IDOC-XI-FILE sceanrio, <b>Is it possible to generate .txt file name based on Plant number like</b> <b>%<Plantname>%_%<BusinessDay>_filename.txt</b> <b>Note:I have implemneted th

  • Renaming Subclip

    When I re-name a subclip it changes the name of the parent clip as well. Any suggestions how I can re-name it without changing the parent clip name?

  • Duplication of calendars with MobileMe

    Hello, thanks for taking the time to read my question.  Problem. I'm having trouble with controlling calendars on my iPhone, I have duplications of whole calendars and can't seem to fathom how to remove them without losing data. Occasionally I create