java gui将文本文件数据导入jtable

7lrncoxx  于 2021-07-09  发布在  Java
关注(0)|答案(0)|浏览(214)

我正在为我的任务编写一个程序,它应该从gui(jtextfield)获取一些用户输入数据到一个文本文件,然后从文本文件检索这些数据到另一个gui(jtable)。
我有一些关于文件处理和JavaSwing的基本知识,现在我遇到了一些问题。
首先,请让我告诉你我现在做了什么(代码如下)。
追加数据

public void actionPerformed(ActionEvent ae) {
        //once clicked the button write the file
        Object[] cols = new Object[]{
                model.getText(),
                make.getText(),
                year.getText()
        };

        try {

            FileOutputStream fstream = new FileOutputStream("words.txt", true);
            ObjectOutputStream outputFile = new ObjectOutputStream(fstream);

            outputFile.writeObject(cols);

            //bw.close();
            outputFile.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

将word文件中的数据读入jtable

public class read extends JFrame {

    JTable table = new JTable();
    JScrollPane pane;
    Object[] cols = null;

    public read() throws ClassNotFoundException, IOException {

        cols = new String[]{"c1", "c2", "c3",};

        DefaultTableModel model = (DefaultTableModel) table.getModel();

        model.setColumnIdentifiers(cols);

        File f = new File("words.txt");
        FileInputStream fis = new FileInputStream(f);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Object[] data = (Object[]) ois.readObject();
        model.addRow(data);

        pane = new JScrollPane(table);
        pane.setBounds(100, 150, 300, 300);

        setLayout(null);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setLocationRelativeTo(null);
        setSize(500, 500);
    }

    public static void main(String[] args) throws ClassNotFoundException, IOException {
        new read();
    }
}

它现在正在工作,但它只从文件中检索一段数据,我希望它显示添加到文件中的所有数据。
我的问题是:
我的words文件看起来不同:

我不确定是我自己还是应该是什么样的人?因为我希望它应该是我写的东西,所以即使addrow(object)方法不起作用,我也可以使用getline添加行。
(重要)因为我在words文件中写入了多个不同的数据(如上图所示),但它只显示一个。我假设这是因为我应该在read.java中向表中添加一个对象数组,而不只是addrow(object),但我不知道如何让数组识别words文件中有很多对象。另外,可以将数据作为对象写入文件并在read.java中检索它们吗,这是正确的方法吗?
谁能告诉我怎么做,谢谢你的帮助。如果我说得不好,请不要犹豫。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题