Passing TableModel to a JTable

<b>I created a personal tableModel class.
I called it with that code :</b>
tableModels[0]=new MyTableModel(data1);
<b>and any time I have this exception:</b>
Exception in thread "main" java.lang.NullPointerException:
at MyTableModel.getRowCount(MyTableModel.java:25)
at javax.swing.table.DefaultTableModel.setNumRows(DefaultTableModel.java
:317)
at javax.swing.table.DefaultTableModel.<init>(DefaultTableModel.java:105
at javax.swing.table.DefaultTableModel.<init>(DefaultTableModel.java:70)
at MyTableModel.<init>(MyTableModel.java:11)
at SwingWinc.layoutComponents(SwingWinc.java, Compiled Code)
at SwingWinc.buildGUI(SwingWinc.java:194)
at SwingWinc.<init>(SwingWinc.java, Compiled Code)
at SwingWinc.main(SwingWinc.java:504)
<b>Why ? please help.
Follow the MyTableModel class </b>
import javax.swing.table.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
public class MyTableModel extends DefaultTableModel
final String[] columnNames={"Analisi Eseguite","Risultati","Valori di riferimento"};
Object[][] matrixTable={
{"GLICEMIA","150 mg/dl","( 60-110 mg/dl )"},
{"AZOTEMIA","33 mg/dl","( 20- 50 mg/dl )"},
{"COLESTEROLO TOT","291 mg/dl","( 130-200 mg/dl )"},
{"COLESTEROLO HDL"," 60 mg/dl","( 40- 70 mg/dl )"},
{"COLESTEROLO LDL","100 mg/dl","( 0-150 mg/dl )"},
{"Glicemia","88 mg/dl","( 60-110 mg/dl )"},
{"Glicemia","88 mg/dl","( 60-110 mg/dl )"},
{"Glicemia","88 mg/dl","( 60-110 mg/dl )"},
{"Glicemia","88 mg/dl","( 60-110 mg/dl )"},
{"Glicemia","88 mg/dl","( 60-110 mg/dl )"},
{"Glicemia","88 mg/dl","( 60-110 mg/dl )"}} ;;
public MyTableModel(Object [][] matrix)
DefaultTableModel tableModel=new DefaultTableModel(matrix,columnNames);
matrixTable=matrix;
public int getColumnCount()
return columnNames.length;
public int getRowCount()
return matrixTable.length;
public String getColumnName(int col)
return columnNames[col];
public Object getValueAt(int row, int col)
return matrixTable[row][col];
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
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;
public void setValueAt(Object value, int row, int col)
matrixTable[row][col] = value;
fireTableCellUpdated(row, col);
I called it with that
tableModels=new MyTableModel(data1);

Hi,
is that data1 reference, that you pass, initialized or do you pass perhaps a null-reference there?
Another thing - in your constructor, you never call the super-constructor in order to construct the underlying DefaultTableModel in the correct way. Instead you instantiate a new DefaultTableModel with your parameters, that will exist only in this block and so do really nothing usefull.
The normal way to call the super-constructor is in your case:
public MyTableModel(Object [ ] [ ] matrix) {
super(matrix,columnNames);
tableMatrix=matrix; } // see comments belowAlso it is not correct, to hold an own matrixTable within the DefaultTableModel and overwrite the TableModel interface methods - the DefaultTableModel has an own Vector of Vector structure to hold the table-data - if you pass for example an Object [ ] [ ] in its constructor, the DefaultTableModel builds its dataVector right after it and copy the values for this array into the dataVector.
If you want to use your own datamodel in Object [ ] [ ] form, then I would suggest to make your MyTableModel extend AbstractTableModel - but if you want to use DefaultTableModel and its methods, you should leave the storage of the data to the DefaultTableModel and its dataVector,
that uses a Vector, that contains Vectors, that each contain the celldata of one row. The methods of DefaultTableModel are designed to use that dataVector, they will not work with or even use your matrixTable array, except that the original data is copied into the dataVector, if you change the constructor in the way, I have posted above.
So my advice is, to consult the online tutorial for that - it is really good and you will see, that creating an own TableModel by subclassing AbstractTableModel is relative easy to do. You have the basic steps done in your implementation (if it would be no DefaultTableModel, that would be a good start for that). So, I guess, you will figure it out, If you read the tutorial about the use of JTable. Start here:
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
greetings Marsian

Similar Messages

  • Getting the TableModel of a JTable

    Hi there!
    I've got a JTable that was created via a class JCatalogTable that extends a so called JAbstractTable (this class extends JTable). In JCatalogTable the AbstractTableModel is set via super(TableModel) to the JAbstractTable. The AbstractTableModel is not the "normal" AbstractTableModel but a class called CatalogTableModel extending the AbstractTableModel.
    This classes are all extending the normal Model because they display a special type of data. However, there is Method in the CatalogTableModel I have to call. My problem now is to get the Model to call the method.
    What I have is an instance of JAbstractTable (a JTable). But I can only get the standard AbstractTableModel, if I try to cast to the CatalogTableModel I get a ClassCastException. Maybe anyone understands what I want and can give me a hin how to solve.
    At last, here is my relevant code:
    // jt_c is the JTable I'm working on
             JAbstractTable jat_c = (JAbstractTable) jt_c;
             AbstractTableModel atm_jat_c = (AbstractTableModel) jat_c.getModel(); // this works
             CatalogTableModel ctm_jat_c = (CatalogTableModel) atm_jat_c; // this gives a class cast exception

    Well, it prints
    class data.swing.CatalogTableModelBut I now wrote a get-Method in the JAbstractTable getATM()
        public AbstractTableModel getATM() {
             return atm; // atm is declared in the whole class
        }and then with
    CatalogTableModel cm = (CatalogTableModel) jat_c.getATM();I have the CatalogTableModel.
    Thanks for your contributions!

  • RemoveColumn from TableModel not just JTable

    I do something like this to remove a column from my JTable:
    JTable.removeColumn(getColumn(columnName));This works great for removing the column from the table...but it doesn't remove the column from the TableModel so if you do a repaint the column come back. There is no
    JTableModel.removeColumn()How can I remove my column from the model?
    PS...How dumb...why would you still want the column in the TableModel after you remove it!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    I would guess 90% of time people what to removeColumn from both Table and Model so why not accommodate the 90% AND 10%. NOT just the 10%.Then why build the TableModel with the data to begin with? Its much faster to simply remove a column from display on the table then it is to recreate the entire TableModel, especially if you need to do a remote database query. So build the TableModel with all the information and let the users customize the view themselves.
    I think you've got your percentages reversed.

  • Deleting a row from a JTable using a custom TableModel

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

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

  • Deleting a row from JTable

    I am trying to delete a row from a JTable whenever the button on the last column is pressed. I know to do this, I can use the removeRow(int) method of the tableModel. But the odd thing is when I try to get a handle to the TableModel from the JTable to use that function, i.e. table.getModel().removeRow(int) it doesn't work. But if I explicitly pass in the tableModel into my class it does work. Here's the code below:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.UIManager;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableCellEditor;
    import javax.swing.AbstractCellEditor;
    import javax.swing.table.DefaultTableModel;
    public class tester4 extends JFrame
         protected final int BUTTON_COL = 2;
         private TableCellRenderer defaultRenderer;
         private TableCellEditor defaultEditor;
         private JTable workingTable;
         private String[] transactionCols = {"Qty", "Product", "Cancel"};
         private Object[][] data = {{5, "prod1", "Cancel"},
                   {6, "prod2", "Cancel"},
                   {7, "prod3", "Cancel"}};
        public tester4()
              workingTable = new JTable(tableModel);
              workingTable.setName("Working Table");
              defaultRenderer = workingTable.getDefaultRenderer(JButton.class);
              defaultEditor = workingTable.getDefaultEditor(Object.class);
              StatusTableRenderer testRenderer = new StatusTableRenderer(defaultRenderer, defaultEditor, workingTable, tableModel);
              workingTable.setDefaultRenderer(Object.class, testRenderer);
              workingTable.setDefaultEditor(Object.class, testRenderer);
            JScrollPane scrollPane = new JScrollPane( workingTable );
            getContentPane().add( scrollPane );
         private DefaultTableModel tableModel = new DefaultTableModel(data, transactionCols){
              // Only allow button column to be editable, if there is an actual
              // button in that row          
              public boolean isCellEditable(int row, int col){
                   return (col == BUTTON_COL && data[row][col] != "") ? true : false;
              // Overriden getColumnClass method that will return the object
              // class type of the first instance of the data type otherwise
              // returns the Object.class
              public Class getColumnClass(int column){
                for (int row = 0; row < getRowCount(); row++){
                    Object o = getValueAt(row, column);
                    if (o != null){ return o.getClass(); }
                return Object.class;
        public static void main(String[] args)
            tester4 frame = new tester4();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
        public class StatusTableRenderer extends AbstractCellEditor
                                                implements TableCellRenderer,
                                                               TableCellEditor,
                                                               ActionListener{
             private TableCellRenderer defaultRenderer;
             private TableCellEditor defaultEditor;
             private JButton cancelButton;
             private JButton editButton;
             private String text;
             private int buttonColumn;
             private int selectedRow;
             private JTable table;
             private DefaultTableModel tableModel;
             public StatusTableRenderer(TableCellRenderer renderer,
                                           TableCellEditor editor,
                                           JTable table,
                                           DefaultTableModel tableModel){
                  defaultRenderer = renderer;
                  defaultEditor = editor;
                  this.table = table;
                  this.tableModel = tableModel;
                  buttonColumn = table.getColumnCount() - 1;
                cancelButton = new JButton();
                editButton = new JButton();
                editButton.setFocusPainted(true);
                editButton.addActionListener(this);
             public StatusTableRenderer(TableCellRenderer renderer,
                                                TableCellEditor editor,
                                                JTable table,
                                                DefaultTableModel tableModel,
                                                int _buttonColumn){
                  this(renderer, editor, table, tableModel);
                  buttonColumn = _buttonColumn;
             public Component getTableCellRendererComponent(JTable table, Object value,
                       boolean isSelected, boolean hasFocus, int row, int column) {
                  if (column == buttonColumn){
                       if (hasFocus){
                            cancelButton.setForeground(table.getForeground());
                            cancelButton.setBackground(UIManager.getColor("Button.background"));
                       else if (isSelected){
                            cancelButton.setForeground(table.getSelectionForeground());
                            cancelButton.setBackground(table.getSelectionBackground());
                       else{
                            cancelButton.setForeground(table.getForeground());
                            cancelButton.setBackground(UIManager.getColor("Button.background"));
                       cancelButton.setText( (value == null) ? "" : value.toString() );
                       return cancelButton;
                return defaultRenderer.getTableCellRendererComponent(
                            table, value, isSelected, hasFocus, row, column);
             public Component getTableCellEditorComponent(JTable table, Object value,
                       boolean isSelected, int row, int column){
                  if (column == buttonColumn){
                       text = ((value == null) ? "": value.toString());
                       editButton.setText(text);
                       selectedRow = row;
                       return editButton;
                  return defaultEditor.getTableCellEditorComponent(
                            table, value, isSelected, row, column);
            public Object getCellEditorValue()
                return text;
            public void actionPerformed(ActionEvent e)
                fireEditingStopped();
                // This works
                tableModel.removeRow(selectedRow);
               // This does not work
              //  table.getModel().removeRow(selectedRow);
    }Take a look at the actionPerfformed method. One way of doing it works, one doesn't. Just trying to understand why me getting a handle to the tableModel through the table doesn't work.
    Message was edited by:
    deadseasquirrels

    It gives me a run-time error Well then your question should be "why do I get this run-time error" and then you would quote the error. Be more descriptive. "It doesn't work" is not descriptive.
    table.getModel().removeRow(selectedRow);I don't use JDK1.5 either. But if you are saying that the above line compiles cleanly with JDK1.5 (because of the auto-boxing feature, or whatever its called), then I see no reason why the code wouldn't work since it recognizes the class as a DefaultTableModel.
    Presumably you commented out the other line so you don't try to delete the row twice. Otherwise you might be getting a indexing error.

  • Can anyone teach me how to create a JTable

    In my project, i would like to make a class extends JTable for which it can function like the excel one.
    This means that the table can split into two parts.
    Each of them have a standalone view and can let user to update the table.

    Had some time to spare so a quick rough example.
    Note this makes use of the TableModel created by JTable when passed an Object[][].
    I'd recommend instead that you create your own TableModel and pass that to both JTables yourself.
    import javax.swing.*;
    import javax.swing.table.*;
    public class SplitTableDemo extends JFrame
       public SplitTableDemo(String title) {
            super(title);
            // prepare data
            int cols = 26;
            int rows = 200;
            Object[][] data = new Object[rows][cols];
            for (int j=0; j<rows; j++) {
                for (int k=0; k<cols; k++) {
                    data[j][k] = new String("");
            // prepare column names
            Object[] columnNames = new Object[cols];
            for (int m=0; m<cols; m++) {
                char c = (char) (65+m);   
                columnNames[m] = String.valueOf(c);
            // create first table view
            JTable upperTable = new JTable(data, columnNames);
            // create second table view with same model (obtained from first)
            TableModel tm = upperTable.getModel();
            JTable lowerTable = new JTable(tm);
            // put tables in ScrollPanes
            JScrollPane upperScroller = new JScrollPane(upperTable);
            JScrollPane lowerScroller = new JScrollPane(lowerTable);
            // display in split pane
            JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upperScroller, lowerScroller);
            this.getContentPane().add(sp);
       public static void main (String[] args)
          SplitTableDemo splitTableDemo = new SplitTableDemo("Split Table Demo");
          splitTableDemo.pack();
          splitTableDemo.show();
    }

  • Custom Cell Renderer for JTable

    Help, I'm trying to write a custom renderer for a column of my JTable but can't get it to work.
    Want I want is a cell in that column to be a label with an Icon and text.
    Trying to test with something simple, just changing colors but even that doesn't work. Can anyone see where I've gone wrong.
    table = new JTable(tableModel);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setShowGrid(false);
    TableColumn tc = table.getColumnModel().getColumn(0);
    tc.setCellRenderer(new DefaultTableCellRenderer() {
       public Component getTableCellRendererComponent(JTable table,
                                                   Object value,
                                                   boolean isSelected,
                                                   boolean hasFocus,
                                                   int row,
                                                   int column)
             JLabel label = (JLabel)
                super.getTableCellRendererComponent
                   (table, value, isSelected, hasFocus, row, column);
                label.setForeground(Color.red);
                label.setBackground(Color.black);
                System.out.println("Object: "+ value);
                return label;
    });Thanks,
    Derek

    Hi
    For colors try :
    all your code
    but where you call super.getTableCellRendererComponent(......
    do only setText(value.toString());
    I supose it is Ok just for changing the colors. If you want render
    an Icon plus some text you can put at your model a JLabel and at this
    render do
    setText((JLabel)value.getText());
    setIcon((JLabel)value.getIcon());
    inside a try/catch clause becasue you can put other kind of object at
    model level
    Or pass instances of an special Class with Icon/Text with publics members set/get to acces to text/icon.
    Hope this help

  • Adding data to a JTable

    how can I add data (Object[][]) to an existing Jtable without creating the Jtable again or setting up a new TableModel for this Jtable.
    Thanks you

    You can't, unless you've written a custom TableModel that allows you to do this.
    The normal solution is:
    DefaultTableModel model = new DefaultTableModel(...);
    table.setModel( model );

  • Problem printing JTable

    here is the code
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    import java.awt.print.PrinterJob;
    import java.awt.print.*;
    // Java extension packages
    import javax.swing.*;
    import javax.swing.table.*;
    class DisplayQueryResultsDOD extends JFrame implements Printable,ActionListener
    ResultSetTableModelDOD tableModel;
    JTextArea queryArea;
    JTable resultTable;
    // create ResultSetTableModel and GUI
    DisplayQueryResultsDOD()
    super( "Displaying Query Results" );
    // Cloudscape database driver class name
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    // URL to connect to books database
    String url = "jdbc:odbc:MyDataSource";
    // query to select entire authors table
    String query = "SELECT * FROM person";
    // create ResultSetTableModel and display database table
         try
    // create TableModel for results of query
    // SELECT * FROM authors
              tableModel =
              new ResultSetTableModelDOD( driver, url, query );
    // set up JTextArea in which user types queries
              queryArea = new JTextArea( query, 3, 100 );
              queryArea.setWrapStyleWord( true );
              queryArea.setLineWrap( true );
              JScrollPane scrollPane = new JScrollPane( queryArea,
              ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
              ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER );
    // set up JButton for submitting queries
              JButton submitButton = new JButton( "Submit Query" );
    // create Box to manage placement of queryArea and
    Box box = Box.createHorizontalBox();
              box.add( scrollPane );
              box.add( submitButton );
    // create JTable delegate for tableModel
              JTable resultTable = new JTable( tableModel );
    // place GUI components on content pane
              Container c = getContentPane();
              c.add( box, BorderLayout.NORTH );
              c.add( new JScrollPane( resultTable ),
              BorderLayout.CENTER );
    // create event listener for submitButton
              submitButton.addActionListener(
         new ActionListener()
         public void actionPerformed( ActionEvent e )
    // perform a new query
         try
              tableModel.setQuery( queryArea.getText() );
    // catch SQLExceptions that occur when
    // performing a new query
         catch ( SQLException sqlException )
              JOptionPane.showMessageDialog( null,sqlException.toString(),"Database error",JOptionPane.ERROR_MESSAGE );
    } // end actionPerformed
    } // end ActionListener inner class
    // set window size and display window
    JMenuBar menuBar = new JMenuBar();
         JMenu filemenu= new JMenu("File");
         JMenu submenux=new JMenu("Open");
         JMenuItem np=new JMenuItem("Launch Panel");
         submenux.add(np);
         //openmenuitem.addActionListener(this);
         submenux.setActionCommand("Open");
         submenux.setMnemonic('O');
         filemenu.add(submenux);
         menuBar.add(filemenu);
         JMenuItem printItem = new JMenuItem("Print");
         printItem.setMnemonic('P');
         filemenu.add(printItem);
         JMenuItem ExitItem = new JMenuItem("Exit");
    ExitItem.setMnemonic('x');
         filemenu.add(ExitItem);
         JMenu viewmenu=new JMenu("View");
         JMenuItem repItem=new JMenuItem("Reports");
         JMenu submenu=new JMenu("sort by");
         submenu.add(new JMenuItem("Marital Status"));
    submenu.add(new JMenuItem("Rank"));
         submenu.add(new JMenuItem("Tribe"));
         submenu.add(new JMenuItem("Educational Level"));
         viewmenu.add(submenu);
         menuBar.add(viewmenu);
         setJMenuBar(menuBar);
    printItem.addActionListener(this);
         ExitItem.addActionListener
         new ActionListener()
    public void actionPerformed(ActionEvent ae)
    System.exit(0);
    setSize( 1500,900);
    // setVisible( true );
    } // end try
    // catch ClassNotFoundException thrown by
    // ResultSetTableModel if database driver not found
         catch ( ClassNotFoundException classNotFound )
         JOptionPane.showMessageDialog( null,"Cloudscape driver not found", "Driver not found",JOptionPane.ERROR_MESSAGE );
              System.exit( 1 ); // terminate application
    // catch SQLException thrown by ResultSetTableModel
    // if problems occur while setting up database
    // connection and querying database
         catch ( SQLException sqlException )
         JOptionPane.showMessageDialog( null,sqlException.toString(),"Database error", JOptionPane.ERROR_MESSAGE );
         System.exit( 1 ); // terminate application
    } // end DisplayQueryResults constructor
         public void actionPerformed(ActionEvent e)
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if (printJob.printDialog())
    try
    printJob.print();
    catch (Exception ex)
    ex.printStackTrace();
         public int print(Graphics g, PageFormat pf, int page) throws
    PrinterException {
    if (page > 0) { /* We have only one page, and 'page' is zero-based */
    return NO_SUCH_PAGE;
    /* User (0,0) is typically outside the imageable area, so we must
    * translate by the X and Y values in the PageFormat to avoid clipping
    Graphics2D g2d = (Graphics2D)g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());
    /* Now print the window and its visible contents */
    resultTable.printAll(g);
    /* tell the caller that this page is part of the printed document */
    return PAGE_EXISTS;
    // execute application
    public static void main( String args[] )
    DisplayQueryResultsDOD app = new DisplayQueryResultsDOD();
    app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    } // end class DisplayQueryResults
    I get an exception
    pls help

    I included this statement only to check if it would print or not, because before that I tried printing the table without setting the size. Anyway, when I tried the same code under Windows it worked fine. Talking about platform independent...:-)

  • Trying to set a JLabel off of a JTable

    Hi! I am trying to let a user select a row from a Jtable and have those highlighted values displayed below in another panel. Problem is that the gui never seems to refresh. Any ideas?
    public class MainClass{
      public static void main( String[] args ){
        JFrame mainFrame = new JFrame( "Main Class" );
        MyTableModel tableModel = new MyTableModel();
        JTable table = new JTable( tableModel );
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        ListSelectionModel rowSM = table.getSelectionModel();
        rowSM.addListSelectionListener( new PanelModel() );
        JScrollPane tableScrollPane = new JScrollPane( table );
        tableScrollPane.setPreferredSize( new Dimension( 80, 80 ) );
        PanelView panelView = new PanelView();
        JScrollPane panelScrollPane = new JScrollPane( panelView );
        panelScrollPane.setPreferredSize( new Dimension(80, 80) );
        mainFrame.getContentPane().add( tableScrollPane, BorderLayout.NORTH );
        mainFrame.getContentPane().add( panelScrollPane, BorderLayout.SOUTH );
        mainFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        mainFrame.pack();
        mainFrame.setVisible( true );
    public class PanelModel implements ListSelectionListener{
      private String anything;
      MyTableModel tableModel = new MyTableModel();
      public void valueChanged(ListSelectionEvent lse) {
        if (lse.getValueIsAdjusting()) return;
        ListSelectionModel lsm = (ListSelectionModel)lse.getSource();
        if (lsm.isSelectionEmpty()) {
          //no rows are selected
        } else {
          int selectedRow = lsm.getMinSelectionIndex();
          String rowValue = (String)tableModel.getValueAt(selectedRow, 0);
          this.populate( rowValue );
      public void populate(String something){
        this.setAnything(something);
        PanelView myPanelView = new PanelView();
        myPanelView.RowInfoField.setText(this.getAnything());
        myPanelView.updateUI();
      public String getAnything() {
        return this.anything;
      public void setAnything( String anything ) {
        this.anything = anything;
    public class MyTableModel extends AbstractTableModel{
      private String[] columns = {"Column 1"};
      private String[][] rows = { {"Something"}, {"Anything"} };
      private static int selectedRow;
      public int getColumnCount(){
        return columns.length;
      public int getRowCount(){
        return rows.length;
      public int getSelectedRow(){
        return selectedRow;
      public Object getValueAt(int r, int c){
        if(rows[r] != null && columns[c] != null){
          return rows[r][c];
        return null;
    public class PanelView  extends JPanel{
      MyTableModel tm;
      int rowSelected = 0;
      private String rowInfo;
      JLabel RowInfoField;
      JLabel RowInfoLabel;
      JPanel panelModel;
      public PanelView() {
        panelModel = new JPanel( new GridLayout() );
        tm = new MyTableModel();
        rowSelected = tm.getSelectedRow();
        rowInfo = (String)tm.getValueAt(rowSelected,0);
        JLabel RowInfoLabel = new JLabel( "RowInfo  " );
        RowInfoLabel.setForeground( Color.black );
        RowInfoField = new JLabel(rowInfo);
        RowInfoField.setFont( new Font( "Serif", 1, 11 ) );
        panelModel.add( RowInfoLabel );
        panelModel.add( RowInfoField );
        this.add( panelModel );
        this.setEnabled( true );
    }

    The problem is in the PanelModel.java line 24. Every time you create new PanelView but not add to the Frame. Following is a quick fix.
    PanelModel.java
    ===================================================================
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class PanelModel implements ListSelectionListener{
    private String anything;
    MyTableModel tableModel = new MyTableModel();
    public void valueChanged(ListSelectionEvent lse) {
    if (lse.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)lse.getSource();
    if (lsm.isSelectionEmpty()) {
    //no rows are selected
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    String rowValue = (String)tableModel.getValueAt(selectedRow, 0);
    this.populate( rowValue );
    public void populate(String something){
              System.out.println("something: " + something);
    this.setAnything(something);
              MainClass.panelView.RowInfoField.setText(this.getAnything());
    // PanelView myPanelView = new PanelView();
    // myPanelView.RowInfoField.setText(this.getAnything());
    // myPanelView.updateUI();
    public String getAnything() {
    return this.anything;
    public void setAnything( String anything ) {
    this.anything = anything;
    ===================================================================
    MainClass.java
    ===================================================================
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class MainClass{
    public static PanelView panelView;
    public static void main( String[] args ){
    JFrame mainFrame = new JFrame( "Main Class" );
    MyTableModel tableModel = new MyTableModel();
    JTable table = new JTable( tableModel );
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener( new PanelModel() );
    JScrollPane tableScrollPane = new JScrollPane( table );
    tableScrollPane.setPreferredSize( new Dimension( 80, 80 ) );
    panelView = new PanelView();
    JScrollPane panelScrollPane = new JScrollPane( panelView );
    panelScrollPane.setPreferredSize( new Dimension(80, 80) );
    mainFrame.getContentPane().add( tableScrollPane, BorderLayout.NORTH );
    mainFrame.getContentPane().add( panelScrollPane, BorderLayout.SOUTH );
    mainFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    mainFrame.pack();
    mainFrame.setVisible( true );
    ===================================================================
    MyTableModel.java
    ===================================================================
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    public class MyTableModel extends AbstractTableModel{
    private String[] columns = {"Column 1"};
    private String[][] rows = { {"Something"}, {"Anything"} };
    private static int selectedRow;
    public int getColumnCount(){
    return columns.length;
    public int getRowCount(){
    return rows.length;
    public int getSelectedRow(){
    return selectedRow;
    public Object getValueAt(int r, int c){
    if(rows[r] != null && columns[c] != null){
    return rows[r][c];
    return null;
    ===================================================================
    PanelView.java
    ===================================================================
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class PanelView extends JPanel{
    MyTableModel tm;
    int rowSelected = 0;
    private String rowInfo;
    JLabel RowInfoField;
    JLabel RowInfoLabel;
    JPanel panelModel;
    public PanelView() {
    panelModel = new JPanel( new GridLayout() );
    tm = new MyTableModel();
    rowSelected = tm.getSelectedRow();
    rowInfo = (String)tm.getValueAt(rowSelected,0);
    JLabel RowInfoLabel = new JLabel( "RowInfo " );
    RowInfoLabel.setForeground( Color.black );
    RowInfoField = new JLabel(rowInfo);
    RowInfoField.setFont( new Font( "Serif", 1, 11 ) );
    panelModel.add( RowInfoLabel );
    panelModel.add( RowInfoField );
    this.add( panelModel );
    this.setEnabled( true );
    ===================================================================

  • TableModel with SORT and GROUP BY functions solution.

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

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

  • Please help - AbstractTableModel, result set and JTable

    Pls help me on this:
    I derive a new class, myTable that extends the AbstractTableModel, one of the member method is like this:
    public void setValueAt( Object data, int row, int col ){
    try{
    resultSet.absolute( row + 1 );
    resultSet.updateDouble( col + 1, Double.parseDouble( data.toString()));
    resultSet.updateRow();
    }//end try
    catch( SQLException sqlEx ){
    JOptionPane.showMessageDialog( null, "SQL error", "", 1 );
    Everytime i try to update the data( which is double), example 2.00, i will see this runtime error:
    java.lang.NumberFormatError: 2.00
    The database is Microsoft Access 2000 and OS is Win ME. I update the data by using JTable GUI( which extends the new class myTable).
    When i try to use Oracle database, then there is no problem for this.
    How to solve this problem?

    can i get a look at your TableModel for the JTable.
    Your problem with Access: Access "double" is not the same as
    Oracle's double.
    you can try the various types that have decimals until you find
    which one access will accept.

  • Updating a Jtable

    Hi,
    im trying to do a music library that connects to mysql.
    My problem is that I dont know how to updatethe table after I have been modifying the database.
    Ex.
    I want to be able to import information to my database and then I want to see the changes instantly.
    At the moment I only see the changes after a restart of the program.
    My code:
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Vector;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.Dimension;
    import functions.*;
    public class MusicLibrary extends JFrame implements ActionListener
         //DEFENITIONS
         JLabel north, south, deepSouth;
         JScrollPane scrollPane,scrollPane2;
         ImageIcon background,top,bottom;
         JTextField searchField;
         JButton searchButton;
         JTable table;
         JMenuBar menuBar;
         JMenu file;
         JMenuItem importSong,removeSong,close;
         Container c;
         public MusicLibrary()
              //MENU
              menuBar = new JMenuBar();
              file = new JMenu("File");
              file.setMnemonic(KeyEvent.VK_F);
              importSong = new JMenuItem("Import Song", KeyEvent.VK_I);
              removeSong = new JMenuItem("Remove Song", KeyEvent.VK_R);
              close = new JMenuItem("Close",KeyEvent.VK_C);
              setJMenuBar(menuBar);
              menuBar.add(file);
              file.add(importSong);
              file.add(removeSong);
              file.addSeparator();
              file.add(close);
              //SOUTH
              background = new ImageIcon("background.gif");
              south = new JLabel (background);
              //NORTH
              top = new ImageIcon("top.gif");
              north = new JLabel(top);
              north.setLayout(new FlowLayout());
              north.setBackground(new Color(0,0,0));
              searchField = new JTextField(50);
              searchButton = new JButton("Search");
              north.add(searchField);
              north.add(searchButton);
              //CONTAINER
              c = getContentPane();
              c.setLayout(new BorderLayout());
              c.add(north, BorderLayout.NORTH);
              setSize(800,620);
              setVisible(true);
              setResizable(false);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              //DEEP SOUTH
              bottom = new ImageIcon("bottom.gif");
              deepSouth = new JLabel(bottom);
              c.add(deepSouth, BorderLayout.SOUTH);
              //LISTENERS
              close.addActionListener(this);
              //searchField.addActionListener(this);
              searchButton.addActionListener(this);
              importSong.addActionListener(this);
              //DATABASE CONNECTION
              try {
                   // load driver, create connection and statement
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   Connection con = DriverManager.getConnection("jdbc:odbc:XXX);
                   Statement stmt = con.createStatement();
                   // query database
                   ResultSet rs = stmt.executeQuery("SELECT * FROM song");
                   // display result
                   getTable(rs);
                   scrollPane = new JScrollPane(table);
                   c.add(scrollPane, BorderLayout.CENTER);
                   // close statement and connection
                   stmt.close();
                   con.close();
              catch (ClassNotFoundException e) {
                   JOptionPane.showMessageDialog(null, e.toString(),
                        "ClassNotFoundException", JOptionPane.ERROR_MESSAGE);
                   System.exit(1);
              catch (SQLException e) {
                   JOptionPane.showMessageDialog(null, e.toString(),
                        "SQLException", JOptionPane.ERROR_MESSAGE);
                   System.exit(1);
              //addWindowListener(new WindowHandler());
              setVisible(true);
         public void actionPerformed (ActionEvent e)
              if(e.getSource()==close)
                   System.exit(0);
              else if(e.getSource()==searchButton)
                   String textsearch = searchField.getText();
                   JOptionPane.showMessageDialog(null,"You searched for " + textsearch);
                   try {
                        // load driver, create connection and statement
                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        Connection con = DriverManager.getConnection("jdbc:odbc:XXX);
                        Statement stmt = con.createStatement();
                        // query database
                        ResultSet rs = stmt.executeQuery("SELECT * FROM song WHERE Song_Name = 'Africa'");
                        // display result
                        getTable(rs);
                        stmt.close();
                        con.close();
                   catch (ClassNotFoundException f) {
                        JOptionPane.showMessageDialog(null, f.toString(),
                             "ClassNotFoundException", JOptionPane.ERROR_MESSAGE);
                        System.exit(1);
                   catch (SQLException f) {
                        JOptionPane.showMessageDialog(null, f.toString(),
                             "SQLException", JOptionPane.ERROR_MESSAGE);
                        System.exit(1);
              else if(e.getSource()==importSong)
                   try
                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        Connection con = DriverManager.getConnection("jdbc:odbc:XXX);
                        EditDatabase.importMp3(con);          
                        //TEST
                        Statement stmt = con.createStatement();
                        // query database
                        ResultSet rs = stmt.executeQuery("SELECT * FROM song");
                        // display result
                        getTable(rs);
                        stmt.close();
                        con.close();
                   catch (Exception q){System.out.println("error" + q);}
              repaint();
         private void getTable(ResultSet rs) throws SQLException
              ResultSetMetaData rsmd = rs.getMetaData();
              Vector cols = new Vector();
              Vector rows = new Vector();
              // get column names
              for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                   cols.addElement(rsmd.getColumnName(i));
              // get rows
              while (rs.next()) {
                   Vector nextRow = new Vector();
                   for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                        nextRow.addElement(rs.getString(i));
                   rows.addElement(nextRow);
              // create table
              table = new JTable(rows, cols);
         //-WINDOW HANDLER-
         private class WindowHandler extends WindowAdapter
              public void windowClosing(WindowEvent e)
                   System.exit(0);
         //-MAIN-
         public static void main (String[] arg)
              new MusicLibrary();
    *Functions is a package containing importMp3 and deleteMp3
    I really appreciate all the help I can get!

    Thanks for poiting in the right direction.
    I had to rethink the design and I stumbled upon some code of yours camickr, thanks.
    Now the code looks like this:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import functions.*;
    public class TableFromDatabase extends JFrame implements ActionListener, TableModelListener
         String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
         String url = "jdbc:odbc:mild";  // if using ODBC Data Source name
         String userid = "frenkan";
         String password = "tfb";
         Container c;
         JTable table;
         JScrollPane scrollPane;
         JMenuItem      importSong,
         removeSong,
         close;
         Connection connection;
         public TableFromDatabase()
              Vector columnNames = new Vector();
              Vector data = new Vector();
              try
                   //  Connect to the Database               
                   Class.forName( driver );
                   Connection connection = DriverManager.getConnection( url, userid, password );
                   //  Read data from a table
                   String sql = "Select * from Song";
                   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 TableModel with databases data
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              //model.addTableModelListener(this);
              //  Create table with model as TableModel
              table = new JTable(model)
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              JPanel buttonPanel = new JPanel();
              c = getContentPane();
              c.add( buttonPanel, BorderLayout.SOUTH );
              //MENU
              JMenuBar menuBar = new JMenuBar();
              JMenu file = new JMenu("File");
              importSong = new JMenuItem("Import Song");
              removeSong = new JMenuItem("Remove Song");
              close = new JMenuItem("Close");
              importSong.addActionListener(this);
              removeSong.addActionListener(this);
              close.addActionListener(this);
              setJMenuBar(menuBar);
              menuBar.add(file);
              file.add(importSong);
              file.add(removeSong);
              file.addSeparator();
              file.add(close);
         public void tableChanged(TableModelEvent e)
         public void actionPerformed (ActionEvent e)
              if (e.getSource() == close)
                   System.exit(0);
              else if (e.getSource() == importSong)
                   try
                        //  Connect to the Database               
                        Class.forName( driver );
                        Connection connection = DriverManager.getConnection( url, userid, password );
                        EditDatabase.importMp3(connection);
                   catch (Exception exception)
                        System.out.println("Fel: " + exception);
         public static void main(String[] args)
              TableFromDatabase frame = new TableFromDatabase();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }Basicly the same as your with some few modifications.
    What I want to know is how to update the table after I have imported a song to the database thru my importMp3() function? Please respond on a basic level. Any help is much appreciated!

  • Dynamically Updating JTable, please help

    I am trying to create an GUI for a java program I wrote to interface with motes running TinyOS. I am having some serious problems creating this because in the JTable tutorial everything is static so I can't figure out how I'm supposed to modify the table from my code. I'm basically reading packets coming in from the serial port and updating several data fields based on what is contained in the packet. I want certain cells in the JTable to reflect the changes that occur in the variables I have, sort of like a debugger would display, but in real time and at full run speed. I tried using the setValueAt function but the problem is the JTable is created in a static method and so I cannot call it from main. I tried moving the section of code that monitors the serial port and updates my data to the createAndShowGUI function, but unfortunately the table will not display unless this function returns, but the program will never return from this function if I move the code there and so I just get a completely grey JTable displayed. I have included the code below, sorry for the length of it but I need some help on this one, I was never taught java and am trying to learn this on my own for research purposes. As it stands now the only error generated by this code is from the following line:
    newContentPane.DataTable.setValueAt("asdfsa",1,1);
    I am not allowed access to newContentPane because it has been dynamically instantiated by createAndShowGUI and I cannot access it through main.
    I'd appreciate any help on this, thank you.
    package net.tinyos.tools;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JComponent;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Date;
    import java.io.*;
    import net.tinyos.packet.*;
    import net.tinyos.util.*;
    import net.tinyos.message.*;
    public class BeaconListen extends JPanel {
    private static int MAX_NODES = 10;
         JTable DataTable;
         public BeaconListen(){
         super(new GridLayout(1,0));     
         Object[] ColumnNames = {"Node","PPS","Average PPS","Time Elapsed"};
         Object[][] Data= {
         {"0","","",""},
         {"1","","",""},
         {"2","","",""},
         {"3","","",""},
         {"4","","",""},
         {"5","","",""},
         {"6","","",""},
         {"7","","",""},
         {"8","","",""},
         {"9","","",""},
         DataTable = new JTable(Data,ColumnNames);
         DataTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
         JScrollPane scrollPane = new JScrollPane(DataTable);
    add(scrollPane);
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI(){
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("MoteData");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    BeaconListen newContentPane = new BeaconListen();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
         if (args.length > 0) {
         System.err.println("usage: java net.tinyos.tools.BeaconListen");
         System.exit(2);
         public static void main(String args[]) {
         //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
                   PacketSource reader = BuildSource.makePacketSource();
         if (reader == null) {
         System.err.println("Invalid packet source (check your MOTECOM environment variable)");
         System.exit(2);
              int i, total = 0;
         int reset =1;
         int packetcount[] = new int[MAX_NODES];
         int PL[] = new int[MAX_NODES];
         int counter[] = new int[MAX_NODES];
         double RSSI[]= new double[MAX_NODES];
         int signalStrength=0;
         double strengthUnsigned=0;
         int Transition=0;
         int PPS=0;
         int FirstRun=1;
         int packetHold=0;
         double avgPacketCount[] = new double[MAX_NODES];
         int secondsElapsed=0;
         int averageReset=1;
         int totalPacketsReceived[] = new int[MAX_NODES];
         System.out.println("Node Listening");
         try {
         reader.open(PrintStreamMessenger.err);
         for(;;){
              byte[] packet = reader.readPacket();
         if(reset==1)
         for(i=0; i<MAX_NODES; i++)
              packetcount=0;
              PL[i]=0;
              counter[i]=0;     
              if(averageReset==1)
              secondsElapsed=0;
              avgPacketCount[i]=0;
              totalPacketsReceived[i]=0;
         reset =0;
         if(FirstRun==0)
         packetcount[packetHold]++;
         totalPacketsReceived[packetHold]++;
         PPS++;
         FirstRun=0;
         averageReset=0;
         packetcount[packet[6]]++;
         totalPacketsReceived[packet[6]]++;
         PPS++;
         strengthUnsigned = ((int)packet[8])& 0xFF;
         RSSI[packet[6]]=RSSI[packet[6]]+strengthUnsigned;
    if((packet[10]==1 && Transition==1) || (packet[10]==0 && Transition==0))
         secondsElapsed++;
         if(Transition==1)
         Transition=0;
         else
         Transition=1;
         PPS--;
         packetcount[packet[6]]--;
         totalPacketsReceived[packet[6]]--;
         packetHold=packet[6];
         reset=1;
         for(i=0; i<MAX_NODES; i++)
         newContentPane.DataTable.setValueAt("asdfsa",1,1);
              System.out.println("Packet Count for Node " + i + "is: " + packetcount[i]);
              PL[i]=8 - packetcount[i];
              System.out.println("Packet Loss for Node " + i + "is: " + PL[i]);
              avgPacketCount[i]=1.0*totalPacketsReceived[i]/secondsElapsed;
              System.out.println("Avg Packet Count for " + secondsElapsed + " seconds is: " +avgPacketCount[i]);
              if(RSSI[i]!=0)
              RSSI[i]=RSSI[i]/packetcount[i];
              RSSI[i]=3*(RSSI[i]/1024);
              RSSI[i]=(-51.3*RSSI[i])-49.2;
              System.out.println("RSSI(dBm) for node " + i + "is: " + RSSI[i]);
              System.out.println();
              packetcount[i]=0;
              RSSI[i]=0;
         System.out.println("Total Packets Recieved: " + PPS);
         PPS=0;
                   System.out.println();
                   System.out.println();
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
         catch (IOException e) {
         System.err.println("Error on " + reader.getName() + ": " + e);

    The best way to update your data is using a TableModel :
    When you instantiate a JTable with an array of objects, it creates a DefaultTableModel which actualy stores your data.
    So, you should create your TableModel, and feed it with the data. Each time the data is updated, the TableModel must notify the JTable, so the new data can be shown :
    here's a simple example
    public class MyModel extends AbstractTableModel
    Object[][] data;
    //you must implement some abstract methods declared in AbstractTableModel
    //the method you use to update the data (you can give it the name you want)
    setData(Object[][] _data)
    data=_data;
    fireTableDataChanged();//method of AbstractTableModel that notifies the data has changed
    public void main(String[] s)
    MyModel tableModel = new MyModel();
    JTable table = new JTable(tableModel);
    JFrame frame = new JFrame();
    frame.getContentPane().add((new JScrollPane()).getViewport().add(table);
    frame.pack();
    frame.setVisible(true);
    tableModel.setData(new Object[][]{{"one", "two"}, {"three", "four"};
    thread.sleep(5000);
    tableModel.setData(new Object[][]{{"five", "six"}, {"seven", "eight};
    You will see the table displaying one, two, three, four, during 5 seconds, and then it will display five, six...

  • How to make a custom TableModel for ResultSet

    Hi,
    I am doing my University Team Project using Java and MySQL what would be the best way to implement a custom TableModel for a JTable that shows the data from the MySQL database.
    I've googled it for a couple of hours but all I can really find is examples of how to add static data into the jTable.
    The updating of the database through Java works fine, but I would like to show the results in a JTable.
    I need help on how to implement a TableModel that uses a ResultSet to populate a JTable.
    Any examples of how to make a custom TableModel or links to something that shos me how to do it would be great.
    Thanks
    Shazan Miah

    I've googled it for a couple of hours but all I can really find is examples of how to add static data into the jTable.Then you need more googling practice on picking the appropriate keywords to narrow down a search. Words like "jtable resultset" yielded many hits. Of course I'm partial to the one I suggested that was found in the Swing forum.

Maybe you are looking for

  • Formatting issues with dbms_xmlgen.getxml()

    Hi, I am trying to get a shell script call a sql code, which tables the tablename as in input parameter and dump out the data as xml format. The basic code works but the xml tags seem broken - $ cat expdata.sql whenever sqlerror exit sqlnum sqlcode s

  • Retrieve deleted files from Time Capsule

    We've got the Time Capsule and I tried to set up user accounts with password for the File Sharing. There's a pop-up window that said something like 'any existing files in the time capsule would be deleted/inaccesible'. I clicked "OK". The thing is my

  • Oracle 10g Database Installation In Active-Passive Mode.

    Good Afternoon !!!! We are installing Oracle 10g in Active-Passive Mode on HP UX-11.3 , with ASM. Can someone help me with step wise installation procedure for the same. Many Thank's Rajeev.

  • Using XML in JDeveloper

    Hi, My application needs to parse a XML format file, could anyone tell me how can I include and use an XML parser in my Jdev application Thank you very much

  • How can I get search to work again in Bridge?

    Stopped working for me about a week ago, just brings up nothing even though I KNOW the file is there. I'm on a Mac using Bridge CC with the latest update.