Inserting data into a JTable?
I am using the netbeans IDE which comes with a very handy GUI creator tool but have run into trouble.
The application that I am creating first queries to a data source and receives that data back in the form of an array of strings. How would I insert this data into the jtable that I have placed into my window using the GUI creator.
I'm not a complete java newbie so I do know about the code behind that GUI and have done swing programming before.
For example, let's say I have two arrays of strings:
String[] tableA_01 = {"Column01","Column02","Column03","Column04"};
String[] tableA_02 = {"Data01","Data02","Data03","Data04"};
How would I insert the first arrays values into the first column and then the second arrays value开发者_运维问答s into a second column, I have not used the JTable component in swing before so I don't really know.
Any help would be much appreciated,
You are doing it all wrong mate, in Jtable's defaultTableModel you can add data very easily. for example
DefaultTableModel table = (DefaultTableModel) myJTable.getModel();
table.addRow{"<column1 value>","<column2 value>"};// maybe even more columns
so from your two arrays i.e.
String[] tableA_01 = {"Column01","Column02","Column03","Column04"};
String[] tableA_02 = {"Data01","Data02","Data03","Data04"};
make arrays like
String[] row1 = {"Column01","Data01"};
String[] row2 = {"Column02","Data02"};
String[] row3 = {"Column03","Data03"};
String[] row4 = {"Column04","Data04"};
looks tedious but you can put this in a loop and update by using
table.addRow(row1);
The data doesn't go into the JTable
directly; instead it goes into the TableModel
. You can use a DefaultTableModel
or you can create your own implementation.
It's pretty easy to subclass AbstractTableModel
if DefaultTableModel
doesn't do what you want.
If you've done Swing programming before, you should know that GUI components are backed by separate model classes. For simple components like text fields, you can get by without dealing with those much, but for a table, you have to deal with the TableModel
. You can use DefaultTableModel
directly - it even has a constructor that takes a two-dimensional array.
Well I doubt you would use them as data for columns. Instead it looks like the first array will be "header" values for 4 columns and then the second array will be "data" values for those 4 columns.
Your code would be something like:
DefaultTableModel model = new DefaultTableModel( tablea_01, tableA_02);
JTable table = new JTable( model );
Read the JTable API and follow the link to the Swing tutorial on "How to Use Tables" for more information and working examples.
精彩评论