I've been trying to find answer for this question for two hours already, but couldn't find working answer.
I'm using NetBeans and JTable
. I need to add or remove rows dynamically depending on value of JSpinner
.
This is NetBeans' uneditable code:
tblPodaci.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
) {
Class[] types = new Class [] {
java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex]; //this is line 83
}
});
This is code that I use to set number of columns:
void spnKValueChanged(ChangeEvent e){
int k = (int)spnK.getValue();
if(k == tblPodaci.getColumnCount()){
return;
}
if(k < tblPodaci.getColumnCount()){
((DefaultTableModel) tblPodaci.getModel()).setColumnCount(k);
}else{
Object[] data = new Integer[tblPodaci.getRowCount()];
((DefaultTableModel) tblPodaci.getModel()).addColumn(" ", data);
}
}
I hide column headers so I don't care about that, I don't need them.
But this code produces ArrayIndexOutOfBoundException
when I try to add new row. Exception is thrown after call to addColumn
, and this is output (only first few lines):
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 4 at anova.MainWindow$3.getColumnClass(MainWindow.java:83) at javax.swing.JTable.getColumnClass(JTable.java:2697) at javax.swing.JTable.getCellRenderer(JTable.java:5682) at javax.swing.plaf.synth.SynthTableUI.paintCell(SynthTableUI.java:683)
Why is this happening? How can I accomplish what I want? I don't really want to implement my own TableModel
(which means writing tone of error prone boiler plate code), I'm disappointed in swing already.
I'm not really a GUI person, so I hope you understand. I'm sure that working answer to this question will help thousands of swing developers.
Hope you have answer. Thank you.