我在从1维矢量“ v”转换为2维矢量“ myVector”时遇到问题。如果您能伸出援手并帮助我解决这个问题,将不胜感激。开放任何建议。
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class InsertDataFinal {
public static void main(String args[]) {
Vector<String> v = new Vector<String>(3);
Vector<Vector<String>> myVector = new Vector<Vector<String>>();
int i = 0;
int j = 0;
try {
FileReader fReader = new FileReader("Password.txt");
BufferedReader inFile = new BufferedReader(fReader);
String input;
String[] temp;
while ((input = inFile.readLine()) != null) {
temp = input.split(" ");
for (i = 0; i < temp.length; i++) {
v.add(temp[i]);
}
myVector.add(j, v);
j++;
}
} catch (Exception e) {
System.out.println("ERROR");
}
Vector<String> columnNames = new Vector<String>(3);
columnNames.addElement("Website");
columnNames.addElement("Username");
columnNames.addElement("Password");
DefaultTableModel model = new DefaultTableModel(myVector, columnNames);
JTable table = new JTable();
table.setModel(model);
JScrollPane scrollpane = new JScrollPane(table);
JPanel panel = new JPanel();
panel.add(scrollpane);
JFrame frame = new JFrame();
frame.add(panel, "Center");
frame.pack();
frame.setVisible(true);
}
}
最佳答案
您的示例继续扩展名为Vector<String>
的v
的单个实例。而是,创建一个新实例并将其添加到myVector
。同样,限制变量的范围并捕获最具体的异常。
Vector<Vector<String>> myVector = new Vector<Vector<String>>();
try {
FileReader fReader = new FileReader("temp.txt");
BufferedReader inFile = new BufferedReader(fReader);
String input;
while ((input = inFile.readLine()) != null) {
String[] temp = input.split(" ");
Vector<String> v = new Vector<String>(3);
for (int i = 0; i < temp.length; i++) {
v.add(temp[i]);
}
myVector.add(v);
}
} catch (IOException e) {
e.printStackTrace(System.err);
}