Using TableModelListener

I am having a heck of a time getting a JTable to refresh. The table is getting it's contents from a database. The model I am using is supposed to call tableChanged, when I click a refresh button. However, that method is never being called, and thus, my JTable is never being updated. How does one go about making the tableChanged() method get called? Thanks.

You need to fire the event whenever the table data has changed (either rows are added or removed or anything else). I guess you are not firing the event after reloading the data from the database to the table model. If that is it, then write the following piece of code.
1. If you donot have a separate model of yours, then
((DefaultTableModel)table.getModel()).fireTableDataChanged();2. If you have your own model, then
   myModel.fireTableDataChanged()
   or
   ((MyModel)table.getModel()).fireTableDataChanged()
  

Similar Messages

  • TableModelListener

    Can I use TableModelListener to detect user selection in a Jtable. If not how can detect selections in a Jtable. Anyone please give me a response. Thanks in advance.

    Add a mouse listener and check the
    cell is selected or not,
    ModelListener is for any data content changes
    in the table and not for selection.doesn't work if the user uses keys to navigate through the table

  • Problem in capturing the edited data while the table is sorted

    hi,
    i am using the TableSorter class provided by the sun tutorials to add sorting capability for my JTable. i need to print on the screen, the value of the cell whenever it is updated. so i am using TableModelListener and its tableChanged() method for this purpose. if i edit the data without applying the sorting then its printing fine. But if i edit the data with table sorted in a particular order by clicking on the table header then the tableChanged method is not being called. So some problem lies in the table sorter which is preventing the call to the tableChanged method whenver table it is sorted. Below is my implementation of JTable.
    TableSorter sorter = new TableSorter(new MyTableModel());
    final JTable table = new JTable(sorter);
    table.getModel().addTableModelListener(new
    TableModelListener()
         public void tableChanged(TableModelEvent e)
              int row = e.getFirstRow();
                                               int column = e.getColumn();
              System.out.println("Row: "+row+" Coloumn:  "+column);
    );Hope u understood the problem. plzz help
    thanx

    hi camickr,
    However the row number displayed is always the row of
    the TableModel before the data has been sorted. this is the feature i am trying for and couldnt achieve it. i do want to print the row of tablemodel before data is sorted but i am getting 0 and -1 as row and column numbers.
    I never saw -1 as a column number.
    if you have never seen -1 as column number then just compile and run the code given below. I just added a table model listener to the table model to capture data editing. So if u edit any cell without applying sorting then its row and column number is printed properly but if u sort a particlar column and with sorting on if u edit any cell you will get row No. as 0 and column No. as -1. try running below code and please let me know where the problem exists or post your code which worked without any of the above problems.
    I believe the code was updated in Feb of this year,
    so make sure you have the most recent version.yes i have the latest version of tablesorter.
    below is my source code for table sorting just compile and run it
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.sql.*;
    import javax.swing.table.*;
    import java.util.*;
    class TableSorterDemo extends JFrame
         public TableSorterDemo()
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         TableSorter sorter=new TableSorter(new MyTableModel());
         JTable table=new JTable(sorter);
         sorter.setTableHeader(table.getTableHeader());
         table.getModel().addTableModelListener(new
    TableModelListener()
         public void tableChanged(TableModelEvent e)
              int row = e.getFirstRow();
            int column = e.getColumn();
              System.out.println("Row :"+row+" Column: "+column);
         JScrollPane scrollPane = new JScrollPane(table);
         scrollPane.setBackground(new Color(198,232,189));
         add(scrollPane);
         pack();
         setVisible(true);
          class MyTableModel extends AbstractTableModel {
            final String[] columnNames = {"First Name",
                                          "Last Name",
                                          "Sport",
                                          "# of Years",
                                          "Vegetarian"};
            final 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)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Angela", "Lih",
                 "Teaching high school", new Integer(4), new Boolean(false)}
            public int getColumnCount() {
                return columnNames.length;
            public int getRowCount() {
                return data.length;
            public String getColumnName(int col) {
                return columnNames[col];
            public Object getValueAt(int row, int col) {
                return data[row][col];
             * JTable uses this method to determine the default renderer/
             * editor for each cell.  If we didn't implement this method,
             * then the last column would contain text ("true"/"false"),
             * rather than a check box.
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
             * Don't need to implement this method unless your table's
             * editable.
            public boolean isCellEditable(int row, int col) {
                //Note that the data/cell address is constant,
                //no matter where the cell appears onscreen.
                if (col < 2) {
                    return false;
                } else {
                    return true;
             * Don't need to implement this method unless your table's
             * data can change.
            public void setValueAt(Object value, int row, int col) {
                    data[row][col] = value;
                    fireTableCellUpdated(row, col);
                   //     System.out.println("row "+row+"Col "+col+"Val "+value);
         public static void main(String[] args)
         new TableSorterDemo();
       /*Table Sorter Class*/
    class TableSorter extends AbstractTableModel {
        protected TableModel tableModel;
        public static final int DESCENDING = -1;
        public static final int NOT_SORTED = 0;
        public static final int ASCENDING = 1;
        private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
        public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) o1).compareTo(o2);
        public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(o2.toString());
        private Row[] viewToModel;
        private int[] modelToView;
        private JTableHeader tableHeader;
        private MouseListener mouseListener;
        private TableModelListener tableModelListener;
        private Map columnComparators = new HashMap();
        private java.util.List sortingColumns = new ArrayList();
        public TableSorter() {
            this.mouseListener = new MouseHandler();
            this.tableModelListener = new TableModelHandler();
        public TableSorter(TableModel tableModel) {
            this();
            setTableModel(tableModel);
        public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
            this();
            setTableHeader(tableHeader);
            setTableModel(tableModel);
        private void clearSortingState() {
            viewToModel = null;
            modelToView = null;
        public TableModel getTableModel() {
            return tableModel;
        public void setTableModel(TableModel tableModel) {
            if (this.tableModel != null) {
                this.tableModel.removeTableModelListener(tableModelListener);
            this.tableModel = tableModel;
            if (this.tableModel != null) {
                this.tableModel.addTableModelListener(tableModelListener);
            clearSortingState();
            fireTableStructureChanged();
        public JTableHeader getTableHeader() {
            return tableHeader;
        public void setTableHeader(JTableHeader tableHeader) {
            if (this.tableHeader != null) {
                this.tableHeader.removeMouseListener(mouseListener);
                TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
                if (defaultRenderer instanceof SortableHeaderRenderer) {
                    this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
            this.tableHeader = tableHeader;
            if (this.tableHeader != null) {
                this.tableHeader.addMouseListener(mouseListener);
                this.tableHeader.setDefaultRenderer(
                        new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
        public boolean isSorting() {
            return sortingColumns.size() != 0;
        private Directive getDirective(int column) {
            for (int i = 0; i < sortingColumns.size(); i++) {
                Directive directive = (Directive)sortingColumns.get(i);
                if (directive.column == column) {
                    return directive;
            return EMPTY_DIRECTIVE;
        public int getSortingStatus(int column) {
            return getDirective(column).direction;
        private void sortingStatusChanged() {
            clearSortingState();
            fireTableDataChanged();
            if (tableHeader != null) {
                tableHeader.repaint();
        public void setSortingStatus(int column, int status) {
            Directive directive = getDirective(column);
            if (directive != EMPTY_DIRECTIVE) {
                sortingColumns.remove(directive);
            if (status != NOT_SORTED) {
                sortingColumns.add(new Directive(column, status));
            sortingStatusChanged();
        protected Icon getHeaderRendererIcon(int column, int size) {
            Directive directive = getDirective(column);
            if (directive == EMPTY_DIRECTIVE) {
                return null;
            return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
        private void cancelSorting() {
            sortingColumns.clear();
            sortingStatusChanged();
        public void setColumnComparator(Class type, Comparator comparator) {
            if (comparator == null) {
                columnComparators.remove(type);
            } else {
                columnComparators.put(type, comparator);
        protected Comparator getComparator(int column) {
            Class columnType = tableModel.getColumnClass(column);
            Comparator comparator = (Comparator) columnComparators.get(columnType);
            if (comparator != null) {
                return comparator;
            if (Comparable.class.isAssignableFrom(columnType)) {
                return COMPARABLE_COMAPRATOR;
            return LEXICAL_COMPARATOR;
        private Row[] getViewToModel() {
            if (viewToModel == null) {
                int tableModelRowCount = tableModel.getRowCount();
                viewToModel = new Row[tableModelRowCount];
                for (int row = 0; row < tableModelRowCount; row++) {
                    viewToModel[row] = new Row(row);
                if (isSorting()) {
                    Arrays.sort(viewToModel);
            return viewToModel;
        public int modelIndex(int viewIndex) {
            return getViewToModel()[viewIndex].modelIndex;
        private int[] getModelToView() {
            if (modelToView == null) {
                int n = getViewToModel().length;
                modelToView = new int[n];
                for (int i = 0; i < n; i++) {
                    modelToView[modelIndex(i)] = i;
            return modelToView;
        // TableModel interface methods
        public int getRowCount() {
            return (tableModel == null) ? 0 : tableModel.getRowCount();
        public int getColumnCount() {
            return (tableModel == null) ? 0 : tableModel.getColumnCount();
        public String getColumnName(int column) {
            return tableModel.getColumnName(column);
        public Class getColumnClass(int column) {
            return tableModel.getColumnClass(column);
        public boolean isCellEditable(int row, int column) {
            return tableModel.isCellEditable(modelIndex(row), column);
        public Object getValueAt(int row, int column) {
            return tableModel.getValueAt(modelIndex(row), column);
        public void setValueAt(Object aValue, int row, int column) {
            tableModel.setValueAt(aValue, modelIndex(row), column);
        // Helper classes
        private class Row implements Comparable {
            private int modelIndex;
            public Row(int index) {
                this.modelIndex = index;
            public int compareTo(Object o) {
                int row1 = modelIndex;
                int row2 = ((Row) o).modelIndex;
                for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
                    Directive directive = (Directive) it.next();
                    int column = directive.column;
                    Object o1 = tableModel.getValueAt(row1, column);
                    Object o2 = tableModel.getValueAt(row2, column);
                    int comparison = 0;
                    // Define null less than everything, except null.
                    if (o1 == null && o2 == null) {
                        comparison = 0;
                    } else if (o1 == null) {
                        comparison = -1;
                    } else if (o2 == null) {
                        comparison = 1;
                    } else {
                        comparison = getComparator(column).compare(o1, o2);
                    if (comparison != 0) {
                        return directive.direction == DESCENDING ? -comparison : comparison;
                return 0;
        private class TableModelHandler implements TableModelListener {
            public void tableChanged(TableModelEvent e) {
                // If we're not sorting by anything, just pass the event along.            
                if (!isSorting()) {
                    clearSortingState();
                    fireTableChanged(e);
                    return;
                if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
                    cancelSorting();
                    fireTableChanged(e);
                    return;
                int column = e.getColumn();
                if (e.getFirstRow() == e.getLastRow()
                        && column != TableModelEvent.ALL_COLUMNS
                        && getSortingStatus(column) == NOT_SORTED
                        && modelToView != null) {
                    int viewIndex = getModelToView()[e.getFirstRow()];
                    fireTableChanged(new TableModelEvent(TableSorter.this,
                                                         viewIndex, viewIndex,
                                                         column, e.getType()));
                    return;
                // Something has happened to the data that may have invalidated the row order.
                clearSortingState();
                fireTableDataChanged();
                return;
        private class MouseHandler extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                JTableHeader h = (JTableHeader) e.getSource();
                TableColumnModel columnModel = h.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = columnModel.getColumn(viewColumn).getModelIndex();
                if (column != -1) {
                    int status = getSortingStatus(column);
                    if (!e.isControlDown()) {
                        cancelSorting();
                    // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
                    // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
                    status = status + (e.isShiftDown() ? -1 : 1);
                    status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
                    setSortingStatus(column, status);
        private static class Arrow implements Icon {
            private boolean descending;
            private int size;
            private int priority;
            public Arrow(boolean descending, int size, int priority) {
                this.descending = descending;
                this.size = size;
                this.priority = priority;
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Color color = c == null ? Color.GRAY : c.getBackground();            
                // In a compound sort, make each succesive triangle 20%
                // smaller than the previous one.
                int dx = (int)(size/2*Math.pow(0.8, priority));
                int dy = descending ? dx : -dx;
                // Align icon (roughly) with font baseline.
                y = y + 5*size/6 + (descending ? -dy : 0);
                int shift = descending ? 1 : -1;
                g.translate(x, y);
                // Right diagonal.
                g.setColor(color.darker());
                g.drawLine(dx / 2, dy, 0, 0);
                g.drawLine(dx / 2, dy + shift, 0, shift);
                // Left diagonal.
                g.setColor(color.brighter());
                g.drawLine(dx / 2, dy, dx, 0);
                g.drawLine(dx / 2, dy + shift, dx, shift);
                // Horizontal line.
                if (descending) {
                    g.setColor(color.darker().darker());
                } else {
                    g.setColor(color.brighter().brighter());
                g.drawLine(dx, 0, 0, 0);
                g.setColor(color);
                g.translate(-x, -y);
            public int getIconWidth() {
                return size;
            public int getIconHeight() {
                return size;
        private class SortableHeaderRenderer implements TableCellRenderer {
            private TableCellRenderer tableCellRenderer;
            public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
                this.tableCellRenderer = tableCellRenderer;
            public Component getTableCellRendererComponent(JTable table,
                                                           Object value,
                                                           boolean isSelected,
                                                           boolean hasFocus,
                                                           int row,
                                                           int column) {
                Component c = tableCellRenderer.getTableCellRendererComponent(table,
                        value, isSelected, hasFocus, row, column);
                if (c instanceof JLabel) {
                    JLabel l = (JLabel) c;
                    l.setHorizontalTextPosition(JLabel.LEFT);
                    int modelColumn = table.convertColumnIndexToModel(column);
                    l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
                return c;
        private static class Directive {
            private int column;
            private int direction;
            public Directive(int column, int direction) {
                this.column = column;
                this.direction = direction;
    }

  • Data changes in JTable

    hi experts
    i'm tring to detect the data change in the JTable. The java.sun.com
    gives one ex on this using "TableModelListener". but the program is
    giving errors on using that. I want to detect the data changes
    and also to save the data in its new form. how can i do it??
    Also, if ur having a large table data and the user changes only one cell , do i have to write the whole table back to the database ???
    Ashish

    here is the code. if i write "implements TableModelListener" then
    an error occurs
    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class TableDisplay extends JFrame implements TableModelListener{
    private Connection connection;
    private JTable table;
    public TableDisplay()
    //using JDBC to connect to a Microsoft ODBC database.
    String url = "jdbc:odbc:trial";
    String username = "ashish";
    String password = "ashish";
    // Load the driver to allow connection to the database
    try {
    Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
    connection = DriverManager.getConnection(
    url, username, password );
    catch ( ClassNotFoundException cnfex ) {
    System.err.println(
    "Failed to load JDBC/ODBC driver." );
    cnfex.printStackTrace();
    System.exit( 1 ); // terminate program
    catch ( SQLException sqlex ) {
    System.err.println( "Unable to connect" );
    sqlex.printStackTrace();
    getTable();
    setSize( 500, 350 );
    show();
    private void getTable()
    Statement statement;
    ResultSet resultSet;
    try {
    String query = "SELECT * FROM shippers";
    statement = connection.createStatement();
    resultSet = statement.executeQuery( query );
    displayResultSet( resultSet );
    statement.close();
    catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
    private void displayResultSet( ResultSet rs )
    throws SQLException
    // position to first record
    boolean moreRecords = rs.next();
    // If there are no records, display a message
    if ( ! moreRecords ) {
    JOptionPane.showMessageDialog( this,
    "ResultSet contained no records" );
    setTitle( "No records to display" );
    return;
    Vector columnHeads = new Vector();
    Vector rows = new Vector();
    try {
    // get column heads
    ResultSetMetaData rsmd = rs.getMetaData();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    columnHeads.addElement( rsmd.getColumnName( i ) );
    // get row data
    do {
    rows.addElement( getNextRow( rs, rsmd ) );
    } while ( rs.next() );
    // display table with ResultSet contents
    table = new JTable( rows, columnHeads );
         table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scroller = new JScrollPane( table );
    getContentPane().add(
    scroller, BorderLayout.CENTER );
    validate();
    catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
    private Vector getNextRow( ResultSet rs,
    ResultSetMetaData rsmd )
    throws SQLException
    Vector currentRow = new Vector();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    /* switch( rsmd.getColumnType( i ) ) {
    case Types.VARCHAR:
    currentRow.addElement( rs.getString( i ) );
    break;
    case Types.INTEGER:
    currentRow.addElement(
    new Long( rs.getLong( i ) ) );
    break;
    default:
    System.out.println( "Type was: " +
    rsmd.getColumnTypeName( i ) );
    currentRow.addElement( rs.getString( i ) );
    return currentRow;
    public void shutDown()
    try {
    connection.close();
    catch ( SQLException sqlex ) {
    System.err.println( "Unable to disconnect" );
    sqlex.printStackTrace();
    public static void main( String args[] )
    final TableDisplay app = new TableDisplay();
    app.addWindowListener(
    new WindowAdapter() {
    public void windowClosing( WindowEvent e )
    app.shutDown();
    System.exit( 0 );

  • JTable for a Layman :(

    Hello Everybody
    im doing my final project...I wanted to take a list of input from user against some predefined words e.g user will have to enter a value for each of the following letters: ABCDEGFHKLRN.......... The only way i found to do that was thru table, which i have seeb first time.My idea was to show the user the predefined letters "ABCDEG..etc" in 1st column of the table and take the corresponding values from the user from the 2nd colum of table.
    I had absolutely no idea of how to use a table, i have tried working out by following n reading the tutorial: [[http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data]
    but i am very confused,i am unable to understand what i have to do for my purpose because the tutorial has so many things related to each other.Please help me as soon as possible
    Im using netbeans.... i tried by using tablemodellistener but i was unable to get the value entered in the table,also listener reads the data at runtime, i dont need to read at runtime, i want to process the data after the whole data (the list of values) have been added.... please help i have tried alot

    You're probably using a JTable with a DefaultTableModel (which declares all columns as editable), and the JTable uses a default editor that enables to type Strings. So no, you don't need a specific editor. That approach has drawback though (I didn't get the goal of the app, but it seems undesirable that the user be able to edit the first column), but work on sketching something that works first, and then robustify it afterwards.
    You didn't comment reply #3. Did you get it?
    A JTable has un underlying TableModel, a non-graphical object, which enables to access the "logical content" of each cell: this is the point of the method getValueAt(int row, int column).
    ( EDIT I just discover it: there's a getValueAt(row,col) on JTable itself. There are subtleties with it (reordering of columns), but as a first shot you can use it (immediately after though, you really should invest in understanding the TableModel, as I no serious work can be undertaken on JTable without mastering that). )
    Wrapping up Darryl's and jboeing's posts, you should have thought about:
    - setting up a JButton beside the JTable.
    - an ActionListener on the button, that would iterate over all cells in the "second column", and get the value (probaly casting it to String), and do whatever you want with the values.
    Edited by: jduprez on Sep 25, 2009 8:17 PM

  • JckechBox into JTable -- getselectedrow

    I have a problem with Checkbox into JTable
    My table has checkbox into first column. If I select checkbox, the program open a new JPanel. To do this I have associated an ActionListener to CheckBox that seems to work fine. This is the related code:
    public class AbstractAction implements ActionListener{            
         private static final long serialVersionUID = 1L;     
        public void actionPerformed(ActionEvent evt) {
            JCheckBox cb = (JCheckBox)evt.getSource();
            alarm_NOack_table.getSelectedRow()
            boolean isSel = cb.isSelected();
            if (isSel) {
        } else {
       };As you can see, in the listener I need to know the row number in which there is the selected checkbox, but alarm_NOack_table.getSelectedRow() return always '-1'.
    How can I do?
    Thanks in advance
    Palmis

    hey!!!
    you will have to use TableModelListener
    if you have a look at API
    getSelectedRow()
    Returns the index of the first selected row, -1 if no row is selected.
    it says that only when row is selected. but clicking your check box does not select the whole row. so you need to listen for changes in the table itself. the best would be to write your own table model (extension of AbstractTableModel)
    this is how you should be able to get the change a your row where the change occurred
    public class YourClass implements TableModelListener{
    yourTable.getModel().addTableModelListener(this);
    public void tableChanged(TableModelEvent tme){
              int row = tme.getFirstRow();
              int col = tme.getColumn();
    //if you want your table model then do this
    TableModel tm = (TableModel)tme.getSource();
    }and now you should have the row a column where the change has occurred and that's it
    hope this will help
    v.v.

  • How do I add a TableModelListener using NetBeans IDE 6.0

    I added a JTable using the IDE but I need to be able to detect when someone has changed the value in a cell.
    From reading I found that I need a TableListener and can use TableChanged and GetValueAt but I can not determine how or where I am suppossed to add that code.
    It seems like it should be in the Guarded block because that is the only part of my code where my JTable is in scope.
    I tried adding a TableModelListener in the section of code that I can edit...right above main and the section where the IDE adds lines like these....
    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    So long story short I still can not determine how to add a Listener to my table.
    Is it something I have to edit myself or can the IDE add it? I can only see Mouse and Key Listeners that I can add in the IDE.

    Hi,
    Sorry I don't have a ready answer to your question, which by now you have probably resolved already. One reason you did not receive a timely reply is that this is a Java Studio Enterprise (JSE) forum, and not a NetBeans forum. Although these are two different products, many of the Enterprise features of JSE can be found in the current NetBeans 6.0 product.
    The general place to ask NetBeans questions is at [email protected]
    Regards,
    -Brad Mayer

  • Adding Rows Dynamically using AbstractTableModel

    I would do anything for some help on this one. I have a JTable that has 5 rows within 1 column. After the user gets to the 5th row I want them another row to be added so that they could add informatoin in there. When I do this with the following code below nothing happens and my column count ends up being -1 right after I do this. If anyone could help it this would be a great help. The output in my console when I end up putting information into all the rows up to the 4th one is the following.
    Vector size 0
    column count1
    column count1
    row 0column 0
    row 1column 0
    row 2column 0
    row 3column 0
    row 4column 0
    column count1
    row 4column -1
    /*********This is my AbstractTableModel Class *********/
    package com.ibm.esup.agent.dataqmonitor;
    * @author garbersb
    * This class sets up the Table Model for the Message Input Queue.
    import java.util.*;
    import javax.swing.table.*;
    import javax.swing.*;
    public class QueueTableModel extends DefaultTableModel
         /** Vector where the message information will be kept. */
         Vector data = null;
         /** Number of columns within the input queue table. */
         protected static int NUM_COLUMNS = 1;
         /** Number of rows within the input queue table. */
         protected static int START_NUM_ROWS = 5;
         /** Next row that could be empty. */
         protected int nextEmptyRow = 0;
         /** Number of rows we are at. */
         protected int numRows = 0;
         * @see java.lang.Object#Object()
         * This will end up creating a Vector when this gets created.
         public QueueTableModel()
              data = new Vector();
              System.out.println("Vector size " + data.size());
         * @see javax.swing.table.TableModel#getColumnName(int)
         * This will allow us to get the Column Name.
         public String getColumnName(int column)
              switch (column)
              return "";
         * @see javax.swing.table.TableModel#getColumnCount()
         public synchronized int getColumnCount()
              System.out.println("column count" + NUM_COLUMNS);
              return NUM_COLUMNS;
         * @see javax.swing.table.TableModel#getRowCount()
         public synchronized int getRowCount()
              if (numRows < START_NUM_ROWS)
                   return START_NUM_ROWS;
              else
                   return numRows;
         * @see javax.swing.table.TableModel#getValueAt(int, int)
         public synchronized Object getValueAt(int row, int column)
              try
                   String queue = (String) data.elementAt(row);
                   switch (column)
                        case 0 :
                             return queue;
              catch (Exception e)
              return "";
         * Don't need to implement this method unless your table's
         * editable.
         public boolean isCellEditable(int row, int col)
              return true;
         * Don't need to implement this method unless your table's
         * data can change.
         public void setValueAt(Object value, int row, int col)
              String queueValue = (String) value;
              data.addElement(queueValue);
              fireTableCellUpdated(row, col);
         * * inserts a row at the end of the table model */
         /*public void insertRow(){      
              int length = getRowCount();
              for (int i=0; i<length ; i++)
              //just add blank string values in this instance but your
              //code will initialise a default object no doubt
              data.addElement("");
              //baseData is the vector containing all your row vectors
              fireTableDataChanged();
         public void addRow()
              addRow(data);
              fireTableDataChanged();
         * Method updateQueue.
         * This method will allow us to update the queues with the latest
         * and greatest information of what messages got added or are
         * on the queue and what time the messages occurred.
         * @param monitorMsgObject
         public synchronized void updateQueue(MonitorMessageObject monitorMsgObject)
         public static void main(String[] args)
    /*********** THis is my main gui class that will has a TableListener and ActionHandler inner - classes within *************/
    package com.ibm.esup.agent.dataqmonitor;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.util.Vector;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextField;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableModel;
    import com.ibm.as400.access.AS400;
    import com.ibm.as400.access.AS400Exception;
    import com.ibm.as400.access.AS400SecurityException;
    * @author garbersb *
    * This will allow the user to sign onto a particular system
    * with a valid user id and password.
    public class SignOn extends JFrame
         /** Label for the system name. */
         private JLabel labelSystemName;
         /** Label for the user name. */
         private JLabel labelUserName;
         /** Label for the password. */
         private JLabel labelPassword;
         /** Label for input queue. */
         private JLabel labelInputQueue;
         /** Label for output queue. */
         private JLabel labelOutputQueue;
         /** Text Field for the system name. */
         private JTextField textFieldSystemName;
         /** Text Field for the user name. */
         private JTextField textFieldUserName;
         /** Text Field for the password. */
         private JPasswordField textFieldPassword;
         /** Text Field for the input queue. */
         private JTextField textFieldInputQueue;
         /** Text Field for the output queue. */
         private JTextField textFieldOutputQueue;
         /** Button that will allow the user to submit. */
         private JButton buttonSubmit;
         /** String that will be used for the system name,
         * user name and password. */
         private String systemName, userName, password, inputQueue, outputQueue;
         /** Label for the input table where different queues
         * can be entered. */
         private JLabel labelQueueInput = null;
         /** One Column table where users can enter different
         * queues that they want to view. */
         private JTable tableQueueInput = null;
         /** Scroll pane that will be used to put the
         * table inside of it. */
         private JScrollPane scrollPaneQueueInput = null;
         /** Label for the interval time that they want to
         * check these different queues. */
         private JLabel labelIntervalCheck = null;
         /** Table panel */
         private JPanel panelTable = null;
         /** Text Field where users can enter a number
         * that will end up being the time that this application
         * will check thes queues. (This is in milli-seconds)
         * For example if a user wants to check the queue every 5 minutes
         * they would enter 60000 within this text field. */
         private JTextField textFieldIntveralCheck = null;
         /** Table Model Input Queue */
         private QueueTableModel tableModelInputQueue = null;
         /** AS400 system object that will be used to sign
         * onto an iSeries system. */
         private AS400 system;
         * Method loadGui.
         * This will load the Sign On Frame and will allow the
         * user to enter the information within the Text Field
         * or specify an xml file that has TCP information already
         * in it.
         public void loadGui()
              //Set the Title
              this.setTitle("Sign On to iSeries System");
              Container contentPane = this.getContentPane();
              GridBagLayout gbl = new GridBagLayout();
              GridBagConstraints gbc = new GridBagConstraints();
              gbc.insets = new Insets(10, 10, 10, 10);
              gbc.fill = GridBagConstraints.EAST;
              contentPane.setLayout(gbl);
              labelSystemName = new JLabel("System Name");
              gbc.gridx = 0;
              gbc.gridy = 1;
              gbl.setConstraints(labelSystemName, gbc);
              contentPane.add(labelSystemName);
              textFieldSystemName = new JTextField();
              textFieldSystemName.setColumns(20);
              gbc.gridx = 1;
              gbc.gridy = 1;
              gbc.gridwidth = 4;
              gbl.setConstraints(textFieldSystemName, gbc);
              contentPane.add(textFieldSystemName);
              labelUserName = new JLabel("User Name");
              gbc.gridx = 0;
              gbc.gridy = 2;
              gbl.setConstraints(labelUserName, gbc);
              contentPane.add(labelUserName);
              textFieldUserName = new JTextField();
              textFieldUserName.setColumns(20);
              gbc.gridx = 1;
              gbc.gridy = 2;
              gbc.gridwidth = 4;
              gbl.setConstraints(textFieldUserName, gbc);
              contentPane.add(textFieldUserName);
              labelPassword = new JLabel("Password");
              gbc.gridx = 0;
              gbc.gridy = 3;
              gbl.setConstraints(labelPassword, gbc);
              contentPane.add(labelPassword);
              textFieldPassword = new JPasswordField();
              textFieldPassword.setColumns(20);
              gbc.gridx = 1;
              gbc.gridy = 3;
              gbc.gridwidth = 4;
              gbl.setConstraints(textFieldPassword, gbc);
              contentPane.add(textFieldPassword);
    /*          labelInputQueue = new JLabel("Interval Check");
              gbc.gridx = 0;
              gbc.gridy = 4;
              gbl.setConstraints(labelInputQueue, gbc);
              contentPane.add(labelInputQueue);
              textFieldInputQueue = new JTextField();
              textFieldInputQueue.setColumns(20);
              gbc.gridx = 1;
              gbc.gridy = 4;
              gbc.gridwidth = 4;
              gbl.setConstraints(textFieldInputQueue, gbc);
              contentPane.add(textFieldInputQueue);
              labelInputQueue = new JLabel("Input Queue");
              gbc.gridx = 0;
              gbc.gridy = 4;
              gbl.setConstraints(labelInputQueue, gbc);
              contentPane.add(labelInputQueue);
              textFieldInputQueue = new JTextField();
              textFieldInputQueue.setColumns(20);
              gbc.gridx = 1;
              gbc.gridy = 4;
              gbc.gridwidth = 4;
              gbl.setConstraints(textFieldInputQueue, gbc);
              contentPane.add(textFieldInputQueue);
              labelOutputQueue = new JLabel("Output Queue");
              gbc.gridx = 0;
              gbc.gridy = 5;
              gbl.setConstraints(labelOutputQueue, gbc);
              contentPane.add(labelOutputQueue);
              textFieldOutputQueue = new JTextField();
              textFieldOutputQueue.setColumns(20);
              gbc.gridx = 1;
              gbc.gridy = 5;
              gbc.gridwidth = 4;
              gbl.setConstraints(textFieldOutputQueue, gbc);
              contentPane.add(textFieldOutputQueue);
              labelQueueInput = new JLabel("Input Queues");
              gbc.gridx = 0;
              gbc.gridy = 6;
              gbl.setConstraints(labelQueueInput, gbc);
              contentPane.add(labelQueueInput);
              tableQueueInput= new JTable();
              scrollPaneQueueInput = new JScrollPane(tableQueueInput);
              Dimension tableQueueInputDimension = new Dimension(220, 100);
              scrollPaneQueueInput.setPreferredSize(tableQueueInputDimension);
              gbc.gridx = 1;
              gbc.gridy = 6;
              gbc.gridwidth = 4;
              gbl.setConstraints(scrollPaneQueueInput, gbc);
              contentPane.add(scrollPaneQueueInput);
              //Setting up the table model input queue.
              tableModelInputQueue = new QueueTableModel();
              tableQueueInput.setModel(tableModelInputQueue);
              TableListener tableListener = new TableListener();
              tableModelInputQueue.addTableModelListener(tableListener);          
              buttonSubmit = new JButton("Submit");
              gbc.gridx = 0;
              gbc.gridy = 7;
              gbl.setConstraints(buttonSubmit, gbc);
              contentPane.add(buttonSubmit);
              RunHandler handler = new RunHandler();
              buttonSubmit.addActionListener(handler);
              //For now we will set the text in the
              //input and output queue for the Analyzer
              //Agent.
              textFieldInputQueue.setText("/qsys.lib/qesp.lib/anz_input.dtaq");
              textFieldOutputQueue.setText("/qsys.lib/qesp.lib/anz_output.dtaq");
         private class TableListener implements TableModelListener {
    public TableListener() {
    public void tableChanged(TableModelEvent e) {
    int row = e.getFirstRow();
    int column = e.getColumn();
    String columnName = tableModelInputQueue.getColumnName(column);
    Object data = tableModelInputQueue.getValueAt(row, column);
    System.out.println("row " + row + "column " + column);
    if (row == 4) {
         tableModelInputQueue.addRow();
              * @author garbersb
              * This will end up creating the System object
         * by getting the system name, user id and
         * password from the Text Field values.
         private class RunHandler implements ActionListener
              * @see java.awt.event.ActionListener#actionPerformed(ActionEvent)
              * When the submit button is selected it will cause the
              * action event to do something.
              public void actionPerformed(ActionEvent e)
                   if (e.getSource() == buttonSubmit)
                        //here we will get the system name, user name
                        //and password.
                        systemName = textFieldSystemName.getText().trim();
                        userName = textFieldUserName.getText().trim();
                        char[] passwordCharArray = textFieldPassword.getPassword();
                        String password = new String(passwordCharArray);
                        inputQueue = textFieldInputQueue.getText().trim();
                        outputQueue = textFieldOutputQueue.getText().trim();
                        //here we will create an AS400 Object.
                        try {
                             system = new AS400(systemName, userName, password);
                             system.connectService(AS400.SIGNON);
                        catch (AS400SecurityException as400e) {
                             as400e.toString();
                        catch (IOException ioe) {
                             ioe.toString();
                        //Going to hide the Sign On window now.
                        setVisible(false);
                        //Now we will load the class that monitors
                        //the input and output queues.
                        MonitorDataQueueGui monitorGui = new MonitorDataQueueGui(system, inputQueue, outputQueue);
                        monitorGui.addGui();
                        monitorGui.show();
                        monitorGui.pack();
         public static void main(String[] args)
              SignOn signOn = new SignOn();
              signOn.loadGui();
              signOn.setSize(400, 400);
              signOn.show();
              signOn.pack();
              signOn.setVisible(true);
              signOn.addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
    }

    Well....I ended up using insertRow with the following code within the method.
         public void insertRow(){      
              numRows += 1;
              fireTableDataChanged();
    I changed my method for the getRowCount to the following;
         * @see javax.swing.table.TableModel#getRowCount()
         public synchronized int getRowCount()
              if (numRows < START_NUM_ROWS)
                   numRows = START_NUM_ROWS;
                   return START_NUM_ROWS;
              else
                   return numRows;
    Since I am not scared of deleting rows I think this is fine....After I did this within my SignOn class I have the following within my TableListener inner class.
         private class TableListener implements TableModelListener {
    public TableListener() {
    public void tableChanged(TableModelEvent e) {
    int row = e.getFirstRow();
    int column = e.getColumn();
    String columnName = tableModelInputQueue.getColumnName(column);
    Object data = tableModelInputQueue.getValueAt(row, column);
    System.out.println("row " + row + "column " + column);
    if (row > 4) {
         tableModelInputQueue.insertRow();
    I am wondering if this is the best way to do it. It seems to work now without a problem but like I said...I am wondering if this is the best thing to do. Any advise would be greatly appreciated and I really do appreciate the advise that has already been given to me.

  • TableModelListener doesn't appear to be working

    Hi,
    I have the following code that is called when a menu item is selected. When the method tableChanged is commented out, the table is displayed just fine. With it in, even if the if statements are commented out, it doesn't display. I just get the frame title being displayed.
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.event.TableModelEvent;
    public class updateCurrentHiLo extends JTable implements TableModelListener {
            public updateCurrentHiLo() {
                    super();
                    String[] columnNames = {"Currency",
                                    "Current Hi",
                                    "Current Lo"};
                    Object[][] data = {
                            {"AUD/USD",DataCapture.currentHigh[0], DataCapture.currentLow[0]},
                            {"GBP/USD",DataCapture.currentHigh[1], DataCapture.currentLow[1]},
                            {"EUR/USD",DataCapture.currentHigh[2], DataCapture.currentLow[2]},
                            {"EUR/JPY",DataCapture.currentHigh[3], DataCapture.currentLow[3]},
                            {"USD/JPY",DataCapture.currentHigh[4], DataCapture.currentLow[4]},
                            {"USD/CHF",DataCapture.currentHigh[5], DataCapture.currentLow[5]},
                            {"USD/CAD",DataCapture.currentHigh[6], DataCapture.currentLow[6]},
                            {"NZD/USD",DataCapture.currentHigh[7], DataCapture.currentLow[7]}
                    DefaultTableModel model = new DefaultTableModel(data, columnNames);
                    //model.addTableModelListener( this ); //We can now check whether the table has been updated.
                    setModel(model);
                    //setFont( new Font("Garamond", Font.BOLD, 50));  //Set the look and feel of the table
                    //setRowHeight(50);  //If you change font size don't forget to change the row height.
                    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                    doLayout();
                    setPreferredScrollableViewportSize(getPreferredSize());      
                    model.addTableModelListener( this ); //We can now check whether the table has been updated.
            public void tableChanged(TableModelEvent e)     {
                    TableModel model = getModel();
                    if (e.getType() == TableModelEvent.UPDATE)
                   int row = e.getFirstRow();
                            int column = e.getColumn();
                            /*if ( column == 1 && DhbMath.equals( ((Double)model.getValueAt(row,column)).doubleValue(),DataCapture.currentHigh[row] ) == false ) {
                                    DataCapture.currentHigh[row] = ((Double)model.getValueAt(row,column)).doubleValue();
                                    System.out.println(DataCapture.currentHigh[row]);
                            /*else if ( column == 2 ) {
                                    DataCapture.currentLow[row] = ((Double)model.getValueAt(row,column)).doubleValue();
    }This is the code that calls the table:
    public void actionPerformed(ActionEvent e) {
            JMenuItem source = (JMenuItem)(e.getSource());
            if ( source.getText().equals("Exit") ) {
                    int clickVALUE = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?", "Quit Confirmation", JOptionPane.YES_NO_OPTION);                    
              if (clickVALUE == 0)     {
                         System.exit(0);
            else {
                            if ( source.getActionCommand().equals("HiLo") ) {
                                    //Do summin
                                    JFrame test = new JFrame("Update Current Highs and Lows");
                                    test.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
                                    //JOptionPane.showInputDialog(
                                    updateCurrentHiLo table = new updateCurrentHiLo();
                                    JScrollPane scrollPane = new JScrollPane( table );
                                    test.add( scrollPane );
                                    test.pack();
                              test.setLocationRelativeTo( null );
                              test.setVisible(true);
        }Any help would be appreciated.
    Regards,
    Dave

    Hi,
    I've made a SSCE to illustrate the problem:
    Main class: RateTable.java
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.KeyEvent;
    import javax.swing.JTabbedPane;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.JComponent;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.KeyEvent;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import javax.swing.JTabbedPane;
    import javax.swing.JFrame;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.KeyEvent;
    import java.awt.event.ActionEvent;
    import java.util.Date;
    import java.util.LinkedList;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.text.DecimalFormat;
    import java.text.ParseException;
    import java.util.StringTokenizer;
    import java.net.URL;
    import java.io.*;
    import java.io.*;
    public class RateTable {
        private static void createAndShowGUI() {
            //Create and set up the window.
            MenuCreator createMenu = new MenuCreator();
            JFrame frame = new JFrame("TabbedPaneDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setJMenuBar(createMenu.createMenuBar());
            //Create and set up the content pane.
            JComponent newContentPane = new TabbedPaneDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.getContentPane().add(new TabbedPaneDemo(), BorderLayout.CENTER);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)  throws IOException {
                    createAndShowGUI();
    }SimpleTable.java
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    public class SimpleTable extends JTable {
            public SimpleTable() {
                    super();
                    String[] columnNames = {"Column 1", "Column 2"};
                    Object[][] data = {
                            {"AUD/USD",new Double(0)},
                            {"GBP/USD",new Double(0)},
                    DefaultTableModel model = new DefaultTableModel(data, columnNames);
                    model.addTableModelListener( this ); //We can now check whether the table has been updated.
                    setModel(model);
                    setFont( new Font("Garamond", Font.BOLD, 50));  //Set the look and feel of the table
                    setRowHeight(50);  //If you change font size don't forget to change the row height.
                    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                    doLayout();
    }MenuCreator.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import javax.swing.event.TableModelEvent;
    import java.lang.Number;
    public class MenuCreator implements ActionListener, TableModelListener {
        JTextArea output;
        JScrollPane scrollPane;
        String newline = "\n";
        updateCurrentHiLo table;
        public JMenuBar createMenuBar() {
                    JMenuBar menuBar;
                    JMenu menu, menu2, submenu;
                    JMenuItem menuItem;
                    JRadioButtonMenuItem rbMenuItem;
                    JCheckBoxMenuItem cbMenuItem;
                    //Create the menu bar.
                    menuBar = new JMenuBar();
                    //Build the first menu.
                    menu = new JMenu("RateTable");
                    menu.setMnemonic(KeyEvent.VK_R);
                    menuBar.add(menu);
                    menuItem = new JMenuItem("Update Current High & Low");
                    menuItem.setMnemonic(KeyEvent.VK_U);
                    menuItem.setActionCommand("HiLo");
                    menuItem.addActionListener(this);
                    menu.add(menuItem);
            return menuBar;
        public void actionPerformed(ActionEvent e) {
            JMenuItem source = (JMenuItem)(e.getSource());
            if ( source.getActionCommand().equals("HiLo") ) {
                    JFrame test = new JFrame("Update Current Highs and Lows");
                    test.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
                    table = new updateCurrentHiLo();
                    TableModel model = table.getModel();
                    model.addTableModelListener( this );
                    JScrollPane scrollPane = new JScrollPane( table );
                    test.add( scrollPane );
                    test.pack();
              test.setLocationRelativeTo( null );
              test.setVisible(true);
        public void tableChanged(TableModelEvent e)     {
                    TableModel model = table.getModel();
                    if (e.getType() == TableModelEvent.UPDATE)
                   int row = e.getFirstRow();
                            int column = e.getColumn();
                            System.out.println("Row "+row);
                            System.out.println("Column "+column);
                            if ( column == 1 ) {
                                    Object test = table.getValueAt(row,column);
                                    System.out.println(test);
                                    //If the following line is commented out, we don't have a problem
                                    Double value = (Double)test;
    }updateCurrentHiLo.java
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.event.TableModelEvent;
    public class updateCurrentHiLo extends JTable  {
            public updateCurrentHiLo() {
                    super();
                    String[] columnNames = {"Currency",
                                    "Current Hi",
                                    "Current Lo"};
                    Object[][] data = {
                            {"AUD/USD", new Double(0), new Double(0)},
                            {"GBP/USD", new Double(0), new Double(0)},
                            {"EUR/USD", new Double(0), new Double(0)},
                            {"EUR/JPY", new Double(0), new Double(0)},
                            {"USD/JPY", new Double(0), new Double(0)},
                            {"USD/CHF", new Double(0), new Double(0)},
                            {"USD/CAD", new Double(0), new Double(0)},
                            {"NZD/USD", new Double(0), new Double(0)},
                    TableModel model = new DefaultTableModel(data, columnNames);
                    setModel(model);
                    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                    doLayout();
                    setPreferredScrollableViewportSize(getPreferredSize());      
    }TabbedPaneDemo.java
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import javax.swing.JTabbedPane;
    import javax.swing.JFrame;
    import java.awt.event.*;
    public class TabbedPaneDemo extends JPanel {
        SimpleTable table = new SimpleTable();
        public TabbedPaneDemo() {
            super(new GridLayout(1, 1));
            JTabbedPane tabbedPane = new JTabbedPane();
            //SimpleTable table = new SimpleTable();
            JScrollPane scrollPane = new JScrollPane( table );
            JPanel panel = new JPanel(false);
            panel.add(scrollPane);
            panel.setPreferredSize(new Dimension(410, 50));
            tabbedPane.addTab("Tab 1", null, panel,
                    "Does nothing");
            tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
            //Add the tabbed pane to this panel.
            add(tabbedPane);
            //The following line enables to use scrolling tabs.
            tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
    }Hope someone can help me track down this error.

  • How to use JTable model listener???

    Anyone got idea , how to use table model listener. Can explain in simple example with code?? how to pass back to resultset ??

    Well, your pretty good at asking questions, but not very good at thanking people for the help given to you so I don't think I'll waste too much time helping this time.
    A TableModelListener notifies you when the contents of a cell are changed. So simply take the data from the cell and update your ResultSet. You question is so general I don't know how you expect any more advice than that.

  • Updating a JTable using CachedRowSet data

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

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

  • Hi, I can't use addRow in JTable

    Hi, I can't use addRow in tableModel1.addRow. I am new in Java
    here some code
    public class Class1 extends JInternalFrame implements TableModelListener
    public Class1(Connection srcCN, JFrame getParentFrame) throws SQLException
        try
        cnCus = srcCN;
              stCus = cnCus.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
              strSQL = "SELECT * FROM customer ORDER BY n_customer ASC";
        rsCus = stCus.executeQuery(strSQL);
          jbInit();
        catch(Exception e)
          e.printStackTrace();
      private void jbInit() throws Exception
        jScrollPane1.getViewport().add(jTable1, null);
        DefaultTableModel tableModel1 = MyModel();
        this.setClosable(true);
        this.setTitle("REVISION");
        this.setMaximizable(true);
        this.setSize(new Dimension(800, 600));
        this.setResizable(true);
        this.setIconifiable(true);
        this.addKeyListener(new java.awt.event.KeyAdapter()
            public void keyPressed(KeyEvent e)
              this_keyPressed(e);
    private DefaultTableModel MyModel(){
      DefaultTableModel m = new DefaultTableModel(){
      public void setValueAt(Object value, int iRows, int iCols) {
                        try {
                             rsCus.absolute(iRows + 1);
                             rsCus.updateString(iCols + 1, value.toString());
                             rsCus.updateRow();
                             super.setValueAt(value, iRows, iCols);
                        } catch (SQLException e) {
                   public boolean isCellEditable(int iRows, int iCols) {
                        if (iCols == 0)
                             return false;
                        if (iCols == 1)
                             return false;
                        return true;    
               public void addRow(Vector data){} 
    m.setDataVector(Content, ColumnHeaderName);
    return m;
    private void this_keyPressed(KeyEvent e)
    tableModel1.addRow(new Vector[]{"r5"});

    Here is an example of building a DefaultTableModel using the data in a ResultSet:
    import java.awt.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableFromDatabase extends JFrame
         public TableFromDatabase()
              Vector columnNames = new Vector();
            Vector data = new Vector();
            try
                //  Connect to the Database
                String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    //            String url = "jdbc:odbc:Teenergy";  // if using ODBC Data Source name
                String url =
                    "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/data/database.mdb";
                String userid = "";
                String password = "";
                Class.forName( driver );
                Connection connection = DriverManager.getConnection( url, userid, password );
                //  Read data from a table
                String sql = "Select * from Page";
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery( sql );
                ResultSetMetaData md = rs.getMetaData();
                int columns = md.getColumnCount();
                //  Get column names
                for (int i = 1; i <= columns; i++)
                    columnNames.addElement( md.getColumnName(i) );
                //  Get row data
                while (rs.next())
                    Vector row = new Vector(columns);
                    for (int i = 1; i <= columns; i++)
                        row.addElement( rs.getObject(i) );
                    data.addElement( row );
                rs.close();
                stmt.close();
            catch(Exception e)
                System.out.println( e );
            //  Create table with database data
            JTable table = new JTable(data, columnNames);
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
            JPanel buttonPanel = new JPanel();
            getContentPane().add( buttonPanel, BorderLayout.SOUTH );
        public static void main(String[] args)
            TableFromDatabase frame = new TableFromDatabase();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
    }

  • JTable , TableModelListener problem

    Hi,
    I have a question about using the JTable with a TableModelListener.It might be a very silly question for some but .. Jtable I still haven't got it right ..always get confused
    I have TableModelListener for my Jtable Model .. I want the listener to be called only when the
    data in the editable cell changes .. as per now .. each time I tab through the table cells without even changing the data in the cell .
    Can someone help me how this can be done .. so that the control goes into the listener only when the data in the cell has been changed .
    One more issuse is that .. the listener is called more than once ..
    I have added a addListSelectionListener for the same JTable and each time a particular row in the table
    is selected .. it called more than once
    Can some one help me with this one please
    thanks
    sandsouza

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableProcessing extends JFrame implements TableModelListener
        JTable table;
        public TableProcessing()
            String[] columnNames = {"Item", "Quantity", "Price", "Cost"};
            Object[][] data =
                {"Bread", new Integer(1), new Double(1.11), new Double(1.11)},
                {"Milk", new Integer(1), new Double(2.22), new Double(2.22)},
                {"Tea", new Integer(1), new Double(3.33), new Double(3.33)},
                {"Cofee", new Integer(1), new Double(4.44), new Double(4.44)}
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            model.addTableModelListener( this );
            table = 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;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
         *  The cost is recalculated whenever the quantity or price is changed
        public void tableChanged(TableModelEvent e)
            if (e.getType() == TableModelEvent.UPDATE)
                int row = e.getFirstRow();
                int column = e.getColumn();
                System.out.println(row + " : " + column);
                if (column == 1 || column == 2)
                    int    quantity = ((Integer)table.getModel().getValueAt(row, 1)).intValue();
                    double price = ((Double)table.getModel().getValueAt(row, 2)).doubleValue();
                    Double value = new Double(quantity * price);
                    table.getModel().setValueAt(value, row, 3);
        public static void main(String[] args)
            TableProcessing frame = new TableProcessing();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

  • Dynamic use of JTable

    I have a JTable which holds a number of columns (these are fix). Now my
    problem is that this table can change at any time by an event in the table.
    I create my rows and data by a table model.
    Those anyone have a idea how I can make the JTable dynamic. So I can easly change the number of rows by an event on the table itself or by a event on the Frame?
    Thanks

    Hi,
    I can't see your problem - if you use a subclass of AbstractTableModel for your table model, which has for example n entries (perhaps hold in a Vector of Vector like DefaultTableModel does it) and you have added for example x rows, simply fireTableRowsInserted(n,n+x-1) of the table model and JTable will update its display correctly. If you delete for example row y simply fireTableRowsDeleted(y,y) - you just have to fire the correct notification message and inform the listeners of the table model about that, what you have done, and the display will keep updated correctly. If you change the whole data vector but keep the structure of the table, simply fireTableDataChanged() - if the data vector and the structure of the table changes, fireTableStructureChanged() - you see, just inform the TableModelListeners about that, what you have done in the table model, and the table will be updated correctly as so the JTable itself is a TableModelListener to its model.
    Perhaps you can be more specific about what your problem is
    greetings Marsian

  • Need a help on TableModelListener.

    Hi,
    I need a help on TableModelListener.
    I have a table in which i have some Double vaules and in a textfield i am summing up the values.
    This table have thousands of record. Already i am summing up the values using for loop and same when i update any value of it.
    So i am searching for a better way. Like pre-event handling. For which i can get a value for a cell before editing and after editing or cell value for row that is deleted.

    We can do sum calculation directly in the TableModel. The method "setValueAt" of the TableModel is called after each cell editing. We can override it to do anything we want with the old value stored in the model and the new value passed into the method through the parameter list. When deleting a row, we also call some method of the model (something like "removeRow") and there again we can do anything we like with the old value before deleting it.

Maybe you are looking for

  • How to setup the default run page in WAR file

    Can anyone please tell me how to setup the default run page in WAR file using JDeveloper? I want the login page to be the default page of the application. Thanks!

  • Setting up a Digital Signature

    Hi all.  I have Adobe Acrobat X, and I'm trying to set up a digital signature with a graphic.  The graphic is actually a signature that is scanned. The problem is when I create the digital signature graphic, the graphic signature is very small and al

  • Hibernate sql-update calling in Java

    Hi, In Hibernate, how to call native <sql-update> in java , since there is no "name" attribute associated with it? Any examples are really appreciated. In Customer.hbm.xml <class ...> <sql-insert> insert into customer (cust_id, firstname, lastname, a

  • When logging into my work webmail, my mac displays tons of blue boxes with question marks in them

    when logging into my work webmail, my mac displays tons of blue question marks - can anybody help?

  • Accessing iOS launch images

    Good day! I'm working on AIR mobile application for iOS. This is a great feature on iOS which can show the static image before the AIR is initialized. But my app has a really lot of content. When the AIR is initialized user can see the black screen f