使用数组中的数据填充一些JTable列

时间:2012-01-27 16:06:25

标签: java swing csv jtable

我有一个csv文件(5列,带|作为分隔符),我想用csv文件中的两个数据列填充2 JTable列。

public class jTable extends JFrame {

    public static int rowNumber() {
        int num = 0;
        try {
            File files = new File("C:\\BorsaItalia2.csv");
            BufferedReader bf = new BufferedReader(new FileReader(files));
            String lines = "";
            while ((lines = bf.readLine()) != null) {
                num++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return num;
    }
    JTable table;

    public jTable() {
        setLayout(new FlowLayout());
        String[] columnNames = {"a", "b", "c", "d", "e"};

        Object[][] data = new Object[rowNumber()][5];

        table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(600, 950));
        table.setFillsViewportHeight(true);

        JScrollPane scroll = new JScrollPane(table);
        add(scroll);
    }

    public static void main(String[] args) {
        try {
            int row = 0;
            int col = 0;

            Object[][] imported = new Object[rowNumber()][5];

            File file = new File("C:\\BorsaItalia2.csv");

            BufferedReader bfr = new BufferedReader(new FileReader(file));
            String line = "";

            while ((line = bfr.readLine()) != null) {

                StringTokenizer st = new StringTokenizer(line, "|");

                col = 0;
                while (st.hasMoreTokens()) {
                    imported[row][col] = st.nextToken();

                    System.out.println("number["+ row + "]["
                        + col + "]:" + imported[row][col]);
                    col++;
                }
                row++;
            }
            bfr.close();

            Object[] description = new Object[imported.length];
            Object[] symbol = new Object[imported.length];

            for (int i = 0; i < imported.length; i++) {
                description[i] = imported[i][2];
                symbol[i] = imported[i][0];
            }
            for (int i = 1; i < imported.length; i++) {
                System.out.println("Description is " + description[i]
                    + " and symbol is: " + symbol[i]);
            }
            System.out.println("");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("error " + e);
        }
        jTable gui = new jTable();
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setSize(650, 950);
        gui.setVisible(true);
        gui.setTitle("Project Table");
    }
}

我想用a填充表格列Object[] symbol,用c填充Object[] description列。

任何编码帮助都非常感谢。

谢谢大家。

1 个答案:

答案 0 :(得分:1)

而不是使用JTable构造函数隐含的DefaultTableModel,而是创建自己的AbstractTableModel实现,如How to Use Tables: Creating a Table Model所示。安排你的getValueAt()从你读过的数组中返回数据。有一个相关的例子here