创建矢量<vector <string>&gt;将.txt文件导入JTable </vector <string>

时间:2013-04-19 17:05:31

标签: java swing vector jtable file-io

我遇到了从1-d矢量“v”转换为2-d矢量“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);
    }
}

1 个答案:

答案 0 :(得分:2)

您的示例继续展开名为Vector<String>的{​​{1}}的单个实例。而是创建一个新实例并将其添加到v。此外,限制变量的范围并捕获最具体的异常。

myVector