My problem is, when I add for example 3 inputs in Vector and when I display the result I only found the last output.
XMLTable, Table,Column = classes
cols : the vector who contain the problem
Code :
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
XMLTable xt= new XMLTable();
Table table = new Table();
Column col = new Column();
Vector<String> txtF = new Vector<String>();
Vector<String> comboF = new Vector<String>();
Vector<Column> cols = new Vector<Column>();
Component[] comp = columns.getComponents();
for(Component c : comp){
if (c instanceof JTextField){
txtF.add(((JTextField) c).getText());
//col.setName(((JTextField) c).getText());
}
else if(c instanceof JComboBox){
comboF.add(((JComboBox<String>) c).getSelectedItem().toString());
//col.setType(((JComboBox<String>) c).getSelectedItem().toString());
}
}
for(int i=0; i<txtF.size();i++){
col.setName(txtF.get(i));
//System.out.println("NAMEE: "+txtF.get(i));
col.setType(comboF.get(i));
//System.out.println("Type: "+comboF.get(i));
cols.add(col);
}
for(int i=0;i<cols.size();i++){
System.out.println("Column : "+i);
System.out.println("name : "+cols.elementAt(i).getName());
System.out.println("type : "+cols.elementAt(i).getType());
}
INPUT :
name : a Type : String
name : b Type : Numeric
name : c Type : String
OUTPUT :
Column : 0
name : c
type : String
Column : 1
name : c
type : String
Column : 2
name : c
type : String
You are adding the same object to
cols
over and over again sincecol
is always the same object. Keep in mind that you handle objects by references (even though Java is always pass-by-value, if you pass an object to a method, you actually pass the object-reference, not the object itself). To fix this, remove the declaration ofColumn col = ...
in the fifth line and change the secondfor loop
to this:This should fix your problem.