Solved

JTable Updating

Posted on 2001-06-14
3
277 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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
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 will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

747 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now