esuslogo
 [To advertise Java(tm) Events here, contact joris@esus.com!]
banner

Java™
by example!






New @ Esus.com


  gb  In-house search engine for better results!

  gb  Get updates with the esus.com
newsletter!









  Home 
 Browse Categories 
 Ask a Java Question 
 Help 
  For Java Tips & Tricks, subscribe to the esus.com newsletter!
Search Java Q&A, Links, API's:   adv 

How do I add a row to a JTable?
The trick is to actaully create an instance of a new javax.swing.table.DefaultTableModel(). You will then have access to the .addRow and .addColumn methods of the TableModel which which will chage the data displayed in your table.

The initComponents() method in the code I pasted below was generated by Forte for Java. Since it does not let you edit the initComponents() method, I just overwrote the generated TableModel with an empty one.




public class TableTest extends javax.swing.JApplet {

public TableTest() {
initComponents ();
javax.swing.table.DefaultTableModel t=new javax.swing.table.DefaultTableModel();
jTable1.setModel (t);
t.addColumn ((Object)"Test");
t.addColumn ((Object)"Foo");
t.addColumn ((Object)"Bar");
t.addRow(new Object[] {"1","2","3"});
t.addRow(new Object[] {"4","5","6"});
t.removeRow(0);
}

private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
getContentPane().setLayout(null);

jTable1.setModel(new javax.swing.table.DefaultTableModel (
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
) {
Class[] types = new Class [] {
java.lang.Object.class,
java.lang.Object.class,
java.lang.Object.class,
java.lang.Object.class
};

public Class getColumnClass (int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);

getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(70, 50, 290, 150);
}

private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
}




Further Information
Author of answer: Nick Ruisi

Comments to this answer are only viewable by members. Login or become a member!





Terms of Service | Privacy Policy | Contact

Copyright © 2000-2003 Esus.com - All Rights Reserved 
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. Esus.com is independent of Sun Microsystems, Inc. All other trademarks are the sole property of their respective owners.