Solved

JTable Updating

Posted on 2001-06-14
3
282 Views
Last Modified: 2010-04-16
Hi friends,

I am trying to create a JTable that continuously updates its displayed values as the underlying data changes. I have tried something like this:

TableModel dataModel = new AbstractTableModel() {    
   public int getColumnCount() { return 4; }
   public int getRowCount() { return 50;}
   public Object getValueAt(int row, int col)
     { return new Integer(row*col);}
};
JTable table = new JTable(dataModel);    

I am not sure how to add real data to this table. I know we can do this:

Object[][] Data;
String[] columnNames;
//initialize Data and columnNames
JTable table = new JTable(Data, columnNames);

but then how do we add the Table Model?
And where do the listeners come in?

I have been running around in the Java API for hours and I cant get to a function that I can actually use :-)

Alfredo


0
Comment
Question by:AlfredoSauce
3 Comments
 
LVL 5

Expert Comment

by:Calron
ID: 6193947
First, you can add the TableModel to the table in two ways: either, in the way that you already do it above, by passing it to the constructor:

JTable table = new JTable(dataModel);

If you do it this way, don't reinitialize the table variable.

The second way is setting it to the table through the setModel() method. Normally.

To initialize the data in the table when you use the constructor method, just initialize the data in your TableModel.

To react to changes in the data you can add a TableModelListener to your table Model. The TableModelListener calls the tableChanged method whenever the data changes in the model.
0
 
LVL 9

Accepted Solution

by:
Ovi earned 150 total points
ID: 6193995
This is the fastest example, a little too much for the question. OK : you have there an inner class which extends JTable an model attached to a table, a table column descriptor class, a specific cell data object. First is created the table. After that is created the model and set'It to the table. On the constructor of the table I create a vector of strings reperesenting the cell values. After all values are know, I call model.addData(Vector data), which will fill the model with the new data and call an updateObjects() method. This method fire an ChangeEvent so the table will be updated. That's all.


import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class SimpleTable extends JFrame {
      private SmartTable table;
      private int rows = 29;
      private int cols = 9;
      
      public SimpleTable() {
            init();
      }
      
      private void init() {
            getContentPane().setLayout(new BorderLayout());
            setSize(400, 300);
            setLocation(300, 100);
            table = new SmartTable();
            getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
            setVisible(true);
      }
      
      class SmartTable extends JTable {
        SmartTableModel model;
   
            public SmartTable() {
                  model = new SmartTableModel();
                  createColumns();
                  setModel(model);
                  setForeground(Color.red);
                  setBackground(new Color(255, 239, 185));
                  setGridColor(Color.orange);
                  setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                  Vector data = new Vector();
                  for(int i=0; i<20; i++) {
                        SmartData[] sd = new SmartData[8];
                        for(int j=0; j<8; j++) {
                              String d = "Cell [" + i + ", " + j + "]";
                              boolean e = (((i%2 == 0) && (j==0|| j==7)) || ((i%2 != 0) && (j==2|| j==5)))?true:false;
                              sd[j] = new SmartData(d, e);
                        }
                        data.addElement(sd);
                  }
                  model.addData(data);
            }
            
            protected void createColumns() {
                  for(int i = 0; i<model.getColumnCount(); i++) {
                        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
                        renderer.setHorizontalAlignment(model.cols[i].alignment);
                        TableColumn column = new TableColumn(i, model.cols[i].width, renderer, null);
                        addColumn(column);
                  }
            }
  }
   
      class SmartTableModel extends AbstractTableModel {
            protected ColumnDescriptor cols[] =  {
                  new ColumnDescriptor("Field1", 40, JLabel.LEFT),
                  new ColumnDescriptor("Field2", 50, JLabel.LEFT),
                  new ColumnDescriptor("Field3", 100, JLabel.LEFT),
                  new ColumnDescriptor("Field4", 60, JLabel.LEFT),
                  new ColumnDescriptor("Field5", 50, JLabel.LEFT),
                  new ColumnDescriptor("Field6", 40, JLabel.LEFT),
                  new ColumnDescriptor("Field7", 40, JLabel.LEFT),
                  new ColumnDescriptor("Field8", 40, JLabel.LEFT),
            };
            protected Vector dObjects;

            public SmartTableModel() {
                  dObjects = new Vector();
            }

            public void addData(Vector v) {
                  dObjects.removeAllElements();
                  for(int i = 0; i<v.size(); i++) {
                        dObjects.addElement((SmartData[]) v.elementAt(i));
                  }
                  updateObjects();
            }
   
    public SmartData getSmartData(int row, int col) {
          return(((SmartData[])dObjects.elementAt(row))[col]);
    }

            protected void updateObjects() {
                  fireTableDataChanged();
            }

            public int getColumnCount() {
                  return(cols.length);
            }

            public int getRowCount() {
                  return(dObjects.size());
            }

            public String getColumnName(int c) {
                  return(cols[c].name);
            }

            public boolean isCellEditable(int row, int col) {
          SmartData[] sd = (SmartData[]) dObjects.elementAt(row);
      return(sd[col].isEditable);
            }

            public Object getValueAt(int row, int col) {
                  if(getRowCount() <= 0)
                        return "";
                  if(row<0||row>=getRowCount())
                        return "";
                  SmartData[] sd = (SmartData[]) dObjects.elementAt(row);
                  switch(col) {
                        case 0: return sd[0].data;
                        case 1: return sd[1].data;
                        case 2: return sd[2].data;
                        case 3: return sd[3].data;
                        case 4: return sd[4].data;
                        case 5: return sd[5].data;
                        case 6: return sd[6].data;
                        case 7: return sd[7].data;
                  }
                  return "";
            }

      }
 
      class ColumnDescriptor {
        public String name;
        public int width;
        public int alignment;
        
        public ColumnDescriptor(String n, int w, int a) {
          name = n;
          width = w;
          alignment = a;
        }
      }
      
  class SmartData {
        String data;
    boolean isEditable;
   
        public SmartData(String d, boolean e) {
          data = d;
      isEditable = e;
        }
  }
 
      public static void main(String[] args) {
            SimpleTable t = new SimpleTable();      
      }
      
}
0
 

Author Comment

by:AlfredoSauce
ID: 6196445
Excellent example my friend!
This does exactly what I want :-)

Thank you very much


Alfredo

0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question