?
Solved

JTable -user input data

Posted on 2003-03-30
24
Medium Priority
?
789 Views
Last Modified: 2011-09-20
Hi,
I was looking through the web about the code using Jtable .I found a lot , most of them already have data fixed using the final object []={"Mary......};

Is there anywhere the said code can be modified so that user can enter data.

Example.

I might need to have a JLabel First Name, a JTextField First Name.
User will enter the name at textfield and the name will be put in the table.

Can anyone help me,?

import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.JOptionPane;
import javax.swing.JApplet;
import java.awt.*;
import java.awt.event.*;

public class TableDemo extends JApplet {
   private boolean DEBUG = true;

   public TableDemo() {
       MyTableModel myModel = new MyTableModel();
       JTable table = new JTable(myModel);
       table.setPreferredScrollableViewportSize(new Dimension(500, 70));

       //Create the scroll pane and add the table to it.
       JScrollPane scrollPane = new JScrollPane(table);

       //Add the scroll pane to this window.
       getContentPane().add(scrollPane, BorderLayout.CENTER);
   }

   class MyTableModel extends AbstractTableModel {
       final String[] columnNames = {"First Name",
                                     "Last Name",
                                     "Sport",
                                     "# of Years",
                                     "Vegetarian"};
       final Object[][] data = {
           {"Mary", "Campione",
            "Snowboarding", new Integer(5), new Boolean(false)},
           {"Alison", "Huml",
            "Rowing", new Integer(3), new Boolean(true)},
           {"Kathy", "Walrath",
            "Chasing toddlers", new Integer(2), new Boolean(false)},
           {"Mark", "Andrews",
            "Speed reading", new Integer(20), new Boolean(true)},
           {"Angela", "Lih",
            "Teaching high school", new Integer(4), new Boolean(false)}
       };

       public int getColumnCount() {
           return columnNames.length;
       }
       
       public int getRowCount() {
           return data.length;
       }

       public String getColumnName(int col) {
           return columnNames[col];
       }

       public Object getValueAt(int row, int col) {
           return data[row][col];
       }

       /*
        * JTable uses this method to determine the default renderer/
        * editor for each cell.  If we didn't implement this method,
        * then the last column would contain text ("true"/"false"),
        * rather than a check box.
        */
       public Class getColumnClass(int c) {
           return getValueAt(0, c).getClass();
       }

       /*
        * Don't need to implement this method unless your table's
        * editable.
        */
       public boolean isCellEditable(int row, int col) {
           //Note that the data/cell address is constant,
           //no matter where the cell appears onscreen.
           if (col < 2) {
               return false;
           } else {
               return true;
           }
       }

       /*
        * Don't need to implement this method unless your table's
        * data can change.
        */
       public void setValueAt(Object value, int row, int col) {
           if (DEBUG) {
               System.out.println("Setting value at " + row + "," + col
                                  + " to " + value
                                  + " (an instance of " 
                                  + value.getClass() + ")");
           }

           if (data[0][col] instanceof Integer                        
                   && !(value instanceof Integer)) {
               //With JFC/Swing 1.1 and JDK 1.2, we need to create    
               //an Integer from the value; otherwise, the column    
               //switches to contain Strings.  Starting with v 1.3,  
               //the table automatically converts value to an Integer,
               //so you only need the code in the 'else' part of this
               //'if' block.
               //XXX: See TableEditDemo.java for a better solution!!!
               try {
                   data[row][col] = new Integer(value.toString());
                   fireTableCellUpdated(row, col);
               } catch (NumberFormatException e) {
                   JOptionPane.showMessageDialog(TableDemo.this,
                       "The \"" + getColumnName(col)
                       + "\" column accepts only integer values.");
               }
           } else {
               data[row][col] = value;
               fireTableCellUpdated(row, col);
           }

           if (DEBUG) {
               System.out.println("New value of data:");
               printDebugData();
           }
       }

       private void printDebugData() {
           int numRows = getRowCount();
           int numCols = getColumnCount();

           for (int i=0; i < numRows; i++) {
               System.out.print("    row " + i + ":");
               for (int j=0; j < numCols; j++) {
                   System.out.print("  " + data[i][j]);
               }
               System.out.println();
           }
           System.out.println("--------------------------");
       }
   }
}
0
Comment
Question by:Jasbir21
[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
  • 14
  • 9
24 Comments
 
LVL 26

Expert Comment

by:ksivananth
ID: 8236878
set the following table model,

    private class NewTabelModel extends DefaultTableModel
    {
      public int getRowCount()
      {
        return ( Vector )getDataVector().size - 1 ;
      }

      public int getColumnCount()
      {
        return ( ( Vector )getDataVector().elementAt( row ) ).size() - 1 ;
      }

      public Object getValueAt( int row, int col )
      {
        return ( ( Vector )getDataVector().elementAt( row ) ).elementAt( col ) ;
      }

      public void setValueAt( Object value, int row, int col )
      {
        // if the value is already added
        if( row < ( Vector )getDataVector().size )
          ( ( Vector )getDataVector().elementAt( row ) ).set( col, value ) ;
        else
          ( ( Vector )getDataVector().elementAt( row ) ).addElement( value ) ;
      }

      public boolean isCellEditable( int row, int col )
      {
        return false ;
      }

    }
0
 

Author Comment

by:Jasbir21
ID: 8237001
I added the class just :

public class TableDemo extends JApplet{

.....


  class MyTableModel extends AbstractTableModel {...}

  private class NewTabelModel extends DefaultTableModel{..}

}

I got the error:

"TableDemo.java" 161L, 4858C written
[root@sentri jas]# javac TableDemo.java
TableDemo.java:133: cannot resolve symbol
symbol  : class DefaultTableModel
location: class TableDemo.NewTabelModel
private class NewTabelModel extends DefaultTableModel{
                                    ^
TableDemo.java:136: cannot resolve symbol
symbol  : class Vector
location: class TableDemo.NewTabelModel
return (Vector)getDataVector().size-1;
        ^
TableDemo.java:136: cannot resolve symbol
symbol  : method getDataVector ()
location: class TableDemo.NewTabelModel
return (Vector)getDataVector().size-1;
               ^
TableDemo.java:139: cannot resolve symbol
symbol  : class Vector
location: class TableDemo.NewTabelModel
return ((Vector)getDataVector().elementAt(row)).size()-1;
         ^
TableDemo.java:139: cannot resolve symbol
symbol  : variable row
location: class TableDemo.NewTabelModel
return ((Vector)getDataVector().elementAt(row)).size()-1;
                                          ^
TableDemo.java:139: cannot resolve symbol
symbol  : method getDataVector ()
location: class TableDemo.NewTabelModel
return ((Vector)getDataVector().elementAt(row)).size()-1;
                ^
TableDemo.java:142: cannot resolve symbol
symbol  : class Vector
location: class TableDemo.NewTabelModel
if(row<(Vector)getDataVector().size)
        ^
TableDemo.java:142: cannot resolve symbol
symbol  : method getDataVector ()
location: class TableDemo.NewTabelModel
if(row<(Vector)getDataVector().size)
               ^
TableDemo.java:143: cannot resolve symbol
symbol  : variable value
location: class TableDemo.NewTabelModel
((Vector)getDataVector().elementAt(row)).set(col,value);
                                                 ^
TableDemo.java:143: cannot resolve symbol
symbol  : class Vector
location: class TableDemo.NewTabelModel
((Vector)getDataVector().elementAt(row)).set(col,value);
  ^
TableDemo.java:143: cannot resolve symbol
symbol  : method getDataVector ()
location: class TableDemo.NewTabelModel
((Vector)getDataVector().elementAt(row)).set(col,value);
         ^
TableDemo.java:145: cannot resolve symbol
symbol  : variable value
location: class TableDemo.NewTabelModel
((Vector)getDataVector().elementAt(row)).addElement(value);
                                                    ^
TableDemo.java:145: cannot resolve symbol
symbol  : class Vector
location: class TableDemo.NewTabelModel
((Vector)getDataVector().elementAt(row)).addElement(value);
  ^
TableDemo.java:145: cannot resolve symbol
symbol  : method getDataVector ()
location: class TableDemo.NewTabelModel
((Vector)getDataVector().elementAt(row)).addElement(value);



0
 

Author Comment

by:Jasbir21
ID: 8237007
Maybe i need to import a class but i didn't.

I have never used JTable before.....
0
Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

 

Author Comment

by:Jasbir21
ID: 8237094
do i still need the abstract table model inside????
0
 
LVL 35

Expert Comment

by:girionis
ID: 8237193
 You need to import the classes missing yes and also to declare the variables used.
0
 

Author Comment

by:Jasbir21
ID: 8237270
...the classses that were missing are:
..import javax.swing.table.DefaultTableModel;
  import java.util.Vector;
......
I guess that there are variables , that are not declared.
I noticed that there was a variable value in the abstaract table and also in the DefaultTableModel .
The variable value in abstaract was defined but the value in DefaultTableModel was not .
What value do i assign it.?????

...I know i need to declare and assign value to size.BUT what should i give it??????



"TableDemo.java" 166L, 4982C written
[root@sentri jas]# javac TableDemo.java
TableDemo.java:141: cannot resolve symbol
symbol  : variable size
location: class java.util.Vector
return (Vector)getDataVector().size-1;
                            ^
TableDemo.java:141: operator - cannot be applied to java.util.Vector,int
return (Vector)getDataVector().size-1;
                                   ^
TableDemo.java:144: cannot resolve symbol
symbol  : variable row
location: class TableDemo.NewTabelModel
return ((Vector)getDataVector().elementAt(row)).size()-1;
                                          ^
TableDemo.java:147: cannot resolve symbol
symbol  : variable size
location: class java.util.Vector
if(row<(Vector)getDataVector().size)
                            ^
TableDemo.java:147: operator < cannot be applied to int,java.util.Vector
if(row<(Vector)getDataVector().size)
      ^
TableDemo.java:148: cannot resolve symbol
symbol  : variable value
location: class TableDemo.NewTabelModel
((Vector)getDataVector().elementAt(row)).set(col,value);
                                                 ^
TableDemo.java:150: cannot resolve symbol
symbol  : variable value
location: class TableDemo.NewTabelModel
((Vector)getDataVector().elementAt(row)).addElement(value);


...HELP, i am sooooooo confuse
0
 
LVL 35

Expert Comment

by:girionis
ID: 8237287
> ...I know i need to declare and assign value to size.BUT what should i give it??????

  This is up to your programme's requirements.

  Change every Vector's "size" variable to "size()" since you are calling a method of the vector class and not an attribute.
0
 

Author Comment

by:Jasbir21
ID: 8237326
I did that and i got less errors :


"TableDemo.java" 166L, 4986C written
[root@sentri jas]# javac TableDemo.java
TableDemo.java:141: inconvertible types
found   : int
required: java.util.Vector
return (Vector)getDataVector().size()-1;
                                   ^
TableDemo.java:144: cannot resolve symbol
symbol  : variable row
location: class TableDemo.NewTabelModel
return ((Vector)getDataVector().elementAt(row)).size()-1;
                                          ^
TableDemo.java:147: inconvertible types
found   : int
required: java.util.Vector
if(row<(Vector)getDataVector().size())
                                   ^
TableDemo.java:148: cannot resolve symbol
symbol  : variable value
location: class TableDemo.NewTabelModel
((Vector)getDataVector().elementAt(row)).set(col,value);
                                                 ^
TableDemo.java:150: cannot resolve symbol
symbol  : variable value
location: class TableDemo.NewTabelModel
((Vector)getDataVector().elementAt(row)).addElement(value);
                                                    ^
0
 
LVL 35

Expert Comment

by:girionis
ID: 8237368
 Change this

 return (Vector)getDataVector().size()-1;

  to this:

  return ((Vector)getDataVector()).size() -1;

  Do likewise for the rest for the error "inconvertible types".

  The rest of the erros you need to declare "value" and "row" variables and give them initial value.
0
 

Author Comment

by:Jasbir21
ID: 8242462
Trying it out
0
 

Author Comment

by:Jasbir21
ID: 8242753
How do i set vectors ??
0
 

Author Comment

by:Jasbir21
ID: 8243005
Anyone ?????
0
 
LVL 35

Expert Comment

by:girionis
ID: 8244070
 What do you mean how do you set vectors?
0
 

Author Comment

by:Jasbir21
ID: 8244565
girionis, i have never used jtable before.

I found a lot of links on abstact table but not many on jtable on defaulttablemodel .

..is there any where you could show a rough code or sample on how to set vectors.

I found two on experts exchange but i didn't get it.

Pls do ... i am soooo lost.

0
 
LVL 35

Accepted Solution

by:
girionis earned 600 total points
ID: 8244683
 You can define a Vector by doing:

  Vector columnNames = new Vector(5);

  You can add data like:

  columnNames.addElement("First Name");
  columnNames.addElement("Last Name");
  columnNames.addElement("Sport");
  columnNames.addElement("# of Years");
  columnNames.addElement("Vegetarian");

  To input data you need to do somethign like:

  Vector data = new Vector();
  Vector row = new Vector(5);
  row.addElement("Mary");
  row.addElement("Campione");
  row.addElement("Snowboarding");
  row.addElement(new Integer(5));
  row.addElement(new Boolean(false));
  data.addElement(row);

  and so on.

  To create the table with the vectors you need to do:

  JTable table = new Jtable(date, columnNames);

  If you still don't get it ask :-)
0
 

Author Comment

by:Jasbir21
ID: 8245289
girionis, sorry for troubling you .

This is my code:      

          import javax.swing.JTable;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.SwingUtilities;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JScrollPane;

import java.util.Vector;
import javax.swing.JApplet;


public class n extends JApplet{
     
     Container pane=getContentPane();
     public n(){
               newtable my=new newtable();
          JTable table=new JTable(my);
          table.setPreferredScrollableViewportSize(new Dimension(500,70));
         
     JScrollPane scrollpane=new JScrollPane(table);
         
getContentPane().add(scrollpane,BorderLayout.CENTER);
          pane.add(table);
         
     }
class newtable extends DefaultTableModel{
     

                   
newtable(){    

         
Vector columnNames=new Vector(5);
               
columnNames.addElement("First Name");
columnNames.addElement("Last Name");
columnNames.addElement("#of Years");
columnNames.addElement("Vegetarian");
Vector data=new Vector();
Vector row=new Vector(5);
         
                              row.addElement("Mary");
     row.addElement("Champione");
     row.addElement("Snowgor");
     row.addElement(new Integer(5));
     row.addElement(new Boolean(false));
     data.addElement(row);
               
JTable table =new JTable(data,columnNames);
     }
     
     
     }    
     public int getRowCount(){
     return ((Vector)getDataVector()).size()-1;
                   
     }
               
public int getColumnCount(){
return ((Vector)getDataVector().elementAt(row)).size()-1;
               }
               
public Object getValueAt(int row, int col){
return((Vector)getDataVector().elementAt(row)).elementAt(col);
               }

public void setValueAt(Object value,int row,int col){
if(row<((Vector)getDataVector()).size())
((Vector)getDataVector().elementAt(row)).set(col,value);

else
((Vector)getDataVector().elementAt(row)).addElement(value);
               }

public boolean isCellEditable(int row,int col){
return false;
}
     }

     }
     


// Is it ok if i put the declaring of the vector in the constructor of the newtable.


//I didn't declare or initialize any variable col,but i didn't get any error.

//When i declared row as vector, when i compiled i got the error:
: elementAt(int) in java.util.Vector cannot be applied to (java.util.Vector)
return ((Vector)getDataVector().elementAt(row)).size()-1;

??? is there anything wrong with the code??

Thanx, forgive me for my blurness

God bless
0
 
LVL 35

Expert Comment

by:girionis
ID: 8245354
>  Is it ok if i put the declaring of the vector in the constructor of the newtable.

  Yes it is, just make sure that it is accessible to the rest of the class. Declare it outside the constructor but initialize it inside the constructor.

> I didn't declare or initialize any variable col,but i didn't get any error

  I guess you are talking about the "col" variable inside the methods. This is fine since they are declared as the method parameters and will be initialized when you call these methods.

> //When i declared row as vector, when i compiled i got the error:
> : elementAt(int) in java.util.Vector cannot be applied to (java.util.Vector)
> return ((Vector)getDataVector().elementAt(row)).size()-1;

  Try changing it to:

  return ((Vector)getDataVector()).elementAt(row).size()-1;

  and see if this works.
0
 

Author Comment

by:Jasbir21
ID: 8245396
Still got the error:: elementAt(int) in java.util.Vector cannot be applied to (java.util.Vector)
     return ((Vector)getDataVector()).elementAt
               ^
(row).size()-1;



0
 
LVL 35

Expert Comment

by:girionis
ID: 8245421
 Are you talking about this method:

public int getColumnCount()
{
  return ((Vector)getDataVector().elementAt(row)).size()-1;
}

  ? I assumed the the getDataVector holds vectors. What is the getDataVector? does it hold vectors or something else?
0
 

Author Comment

by:Jasbir21
ID: 8245605
Don't know....., i got the code  from ksivananth...

..Is there any link, where i could read and try to understand the said table with vectors...

Thanks

0
 
LVL 35

Expert Comment

by:girionis
ID: 8245682
Yes I suggest you understand how Vectors work first and then move to JTables. For a tutorial on Collections look here: http://java.sun.com/docs/books/tutorial/collections/index.html but basically if you do a search on google you will find tons of information. For JTables look here: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html which is a godo place to start.
0
 

Author Comment

by:Jasbir21
ID: 8345082
girionis,
 Hi its me Jasbir ,sorry for posting the points late.

God bless,
Jasbir
0
 

Author Comment

by:Jasbir21
ID: 8345089
Thanks for the help, i am still studying the jtable.

God bless,
0
 
LVL 35

Expert Comment

by:girionis
ID: 8346649
 Thank you. If you need any more help please ask :-)
0

Featured Post

Enroll in August's Course of the Month

August's CompTIA IT Fundamentals course includes 19 hours of basic computer principle modules and prepares you for the certification exam. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

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

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
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 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…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses
Course of the Month10 days, 11 hours left to enroll

765 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