Java adding to table data issue
Can someone tell me, where is my mistake? I'm trying to fill up table with data but I can't, always get empty table. Here is my code with frame:
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Rinktis extends JFrame {
private final JScrollPane scrollPane = new JScrollPane();
private JTable table;
public Rinktis()
开发者_如何转开发 {
super();
setBounds(100, 100, 861, 375);
try {
jbInit();
} catch (Throwable e) {
e.printStackTrace();
}
}
Vector<Vector<String>> data1 =new Vector<Vector<String>>();
Vector<String> heading1 = new Vector<String>();
public void tab(Vector heading, Vector data)
{ System.out.println(data);
System.out.println(heading);
data1=data;
heading1=heading;
System.out.println(data1);
System.out.println(heading1);
}
private void jbInit() throws Exception {
getContentPane().setLayout(null);
getContentPane().add(scrollPane);
scrollPane.setBounds(10, 10, 825, 176);
table = new JTable(data1,heading1);
scrollPane.setViewportView(table);
}
}
Here's how I call it from another frame:
protected void rinktisButton_1_actionPerformed(ActionEvent e)
{ Rinktis frame = new Rinktis();
frame.setVisible(true);
try {
db.getClients();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
and from db.getClients();
I call rinktis.tab(columnHeads,v);
System.out.println
gives me all data correctly, but table is empty.
change your tab function to be like this:
public void tab(Vector heading, Vector data)
{
table.setModel(new DefaultTableModel(data,heading) );
}
For a serius answer you need to post an SSCCE. Anyway it seems that you are passing a wrong type to JTable constructor.
You need to pass a 2d array of object (Object [][]
) or Vector<Vector<Object>>
not plain 1D Vector, same as for TableHeader
I think here's the problem :
table = new JTable(data1, heading1);
//data1 need to of type Object[][] or Vector<Vector<Object>>
//heading1 need to of type String[] or Vector<String>
Here's a tutorial.
The problem is that the table does not know that you changed the data. You can either load your data on creation of the table. Then it should show up just fine (maybe try this out first). Then in a second step you should work directly with the tablemodel and change data there. Whenever you do so call the you can notify the table to update.
Alternatively, if you already know your header, you can set it and only add the data later. This also should work. However I do not recommend this.
精彩评论