有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数组Java GUI将文本文件数据导入JTable

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

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

首先,请让我告诉你我现在做了什么(代码如下)

  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. 我的Word文件看起来不同:

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

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

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

谁能告诉我怎么做,谢谢你的帮助。 如果我说得不好,请尽管问


共 (0) 个答案