netbeans jtable automatic expansion
HOWTO get a NetBeans JTable to automatically expand when it runs out of space. That is, add new rows whenever needed.
Step 1:
Create a normal JTable in NetBeans
Step 2:
Add a PropertyChangeEvent handler to the table via the inspector window.
Right click jTable1 -> Events -> PropertyChange -> propertyChange
This should take you to the source.
Step 3:
Add the following to the PropertyChangeEvent handler:
private void jTable1PropertyChange(java.beans.PropertyChangeEvent evt) {
int last = jTable1.getRowCount(); //count the number of rows already in the table
if (jTable1.getValueAt(last-1,0) == null){ //check if there’s anything in the first column of last row
//first column of last row is empty, so do nothing
}else{ //last row was not empty
Object o[][] = new Object[jTable1.getRowCount()+1][jTable1.getColumnCount()]; //create a new 2D object with size the same as the table+1
for (int i = 0; i < jTable1.getRowCount(); i++){ //loop through the rows
for (int j = 0; j < jTable1.getColumnCount(); j++){ //loop through the columns
o[i][j] = jTable1.getValueAt(i,j); //populate the new Object with values from the table
}
}for (int k = 0; k < jTable1.getColumnCount(); k++){
o[jTable1.getRowCount()][k] = null; //add a null row to the new object
}//set the tables new model with “o” as the first parameter – o is the new object
jTable1.setModel(new javax.swing.table.DefaultTableModel(
o, new String [] {
“Firstname”, “Surname”, “Birthday”
}
)//Create the rest of the table model – copied from generated code
{
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class
};public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
}
}
And that’s it – your table should now automatically expand when necessary.
The same logic can be applied to deleting rows when they’re not needed.
Below is an complete program which shows automatic table expansion in action. It can be downloaded, compiled and executed independently.
Source: TableExpandGUI.java










Hi,
I’m using Net Beans 5.1 and I’m creating a JFrame using the drag and drop of the Components showed in the “Palette”.
Well the problem is : the Property columnCount is only read only and I cannot modify it why ?
Can you help me ?