[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

JTable Updating

Posted on 2001-06-14
3
Medium Priority
?
288 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 600 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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
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 …
Suggested Courses

656 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