Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 849
  • Last Modified:

JTable -user input data

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
Jasbir21
Asked:
Jasbir21
  • 14
  • 9
1 Solution
 
ksivananthCommented:
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
 
Jasbir21Author Commented:
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
 
Jasbir21Author Commented:
Maybe i need to import a class but i didn't.

I have never used JTable before.....
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Jasbir21Author Commented:
do i still need the abstract table model inside????
0
 
girionisCommented:
 You need to import the classes missing yes and also to declare the variables used.
0
 
Jasbir21Author Commented:
...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
 
girionisCommented:
> ...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
 
Jasbir21Author Commented:
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
 
girionisCommented:
 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
 
Jasbir21Author Commented:
Trying it out
0
 
Jasbir21Author Commented:
How do i set vectors ??
0
 
Jasbir21Author Commented:
Anyone ?????
0
 
girionisCommented:
 What do you mean how do you set vectors?
0
 
Jasbir21Author Commented:
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
 
girionisCommented:
 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
 
Jasbir21Author Commented:
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
 
girionisCommented:
>  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
 
Jasbir21Author Commented:
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
 
girionisCommented:
 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
 
Jasbir21Author Commented:
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
 
girionisCommented:
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
 
Jasbir21Author Commented:
girionis,
 Hi its me Jasbir ,sorry for posting the points late.

God bless,
Jasbir
0
 
Jasbir21Author Commented:
Thanks for the help, i am still studying the jtable.

God bless,
0
 
girionisCommented:
 Thank you. If you need any more help please ask :-)
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 14
  • 9
Tackle projects and never again get stuck behind a technical roadblock.
Join Now