Reputation: 683
I've been searching for a few hours now and have been unable to find any neat & clean solution to adding a column/element dynamically to a table model in Java. Perhaps I'm a bad researcher, I don't know. It's been frustrating me, I've read through two different books and found absolutely nothing on the subject. I've pillaged Google's massive database and found nothing of use. I've found some 'solutions' to this for adding a row, but they don't seem so great. I want to be able to dynamically insert rows AND columns. I've invested 5 cups of tea & most of my mental stability into finding this solution, with no victory.
I was thinking of something like this:
rageTableModel.addColumn("No need to be upset anymore!");
rageTableModel.addRow("No need to be upset anymore!");
Maybe there is some increasingly simple solution to my struggles, however I seem to be unable to find it on my own. I'm rather new to Java(2-3 months experience), so it's not as if my knowledge spans that far on the subject. Any help would be appreciated.
EDIT: I see this "addColumn" method used everywhere, and I'm attempting to use it on the object of my AbstractTableModel; no victory. I don't see anything mentioning this method on the doc page. http://docs.oracle.com/javase/7/docs/api/javax/swing/table/AbstractTableModel.html
Upvotes: 3
Views: 285
Reputation: 41
I don't know what you are trying to do but, I think always is better to set the model of the table. Only if you are writing a spread sheet or something like, you can write a button or context menu to add a new column or row. I mean, you should define the headers and call the method defaultTableModel.setColumnIdentifiers(Object[] newIdentifiers)
. Shure, the newIdentifiers object array is a String array.
Doing so you only add Rows of data in order to show the data to the user.
Hope it helps!
Upvotes: 0
Reputation: 9317
Following code works fine for me. If you have implemented your own table model may be it is not firing notifications properly.
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TableTest {
public static void main(String[] args) throws InterruptedException {
JFrame f = new JFrame();
DefaultTableModel m = new DefaultTableModel();
JTable t = new JTable(m);
f.add(new JScrollPane(t), BorderLayout.CENTER);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
m.addColumn("A");
m.addRow(new String[]{"A1"});
Thread.sleep(1000);
m.addColumn("B");
m.addRow(new String[]{"A2", "B2"});
}
}
Upvotes: 2