Solved

JTable Updating

Posted on 2001-06-14
3
284 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

707 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