Solved

JTable Updating

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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
jboss wildfly 10.1 10 425
Running JavaFX on JDeveloper 12C 1 77
Why doesn't this text field show up on my Applet frame? 2 28
Delete .class files at every compile 4 19
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…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This video teaches viewers about errors in exception handling.

749 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