首页 > 解决方案 > Java GUI 将文本文件数据导入 JTable

问题描述

我正在为我的作业编写一个程序,它应该将一些用户输入数据从 GUI(jtextfield) 获取到文本文件,然后将这些数据从文本文件检索到另一个 GUI(JTable)。

我有一些关于文件处理和 JAVA swing 的基本知识,但我现在遇到了一些问题。

首先,请让我告诉我现在做了什么(下面的代码)。

  1. 附加数据
    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();
        }
    }
  1. 从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();
    }
}

它现在正在工作,但它只从文件中检索一条数据,我希望它显示添加到文件中的所有数据。

我的问题是:

  1. 我的文字文件看起来不同:

https://i.stack.imgur.com/RbIVk.png

我不确定它只是我还是它应该是什么?因为我希望它应该与我写的完全一致,所以即使 addrow(object) 方法不起作用,我也可以使用 getline 添加行。

  1. (重要)因为我将多个不同的数据写入单词文件(及其如上图所示),但它只显示一个。我认为这是因为我应该在 read.java 中的表中添加一个对象数组,而不仅仅是 addrow(object) 但我不知道如何,我的意思是我不知道如何让数组识别出有很多对象在单词文件中。另外,可以将数据作为对象写入文件并在 read.java 中检索它们,这是正确的方法吗?

谁能告诉我怎么做,谢谢你的帮助。请不要犹豫,问我是否没有正确说明。

标签: javaarraysswingvectorfile-handling

解决方案


推荐阅读