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

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

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

  1. public void actionPerformed(ActionEvent ae) {
  2. //once clicked the button write the file
  3. Object[] cols = new Object[]{
  4. model.getText(),
  5. make.getText(),
  6. year.getText()
  7. };
  8. try {
  9. FileOutputStream fstream = new FileOutputStream("words.txt", true);
  10. ObjectOutputStream outputFile = new ObjectOutputStream(fstream);
  11. outputFile.writeObject(cols);
  12. //bw.close();
  13. outputFile.close();
  14. } catch (Exception ex) {
  15. ex.printStackTrace();
  16. }
  17. }

将word文件中的数据读入jtable

  1. public class read extends JFrame {
  2. JTable table = new JTable();
  3. JScrollPane pane;
  4. Object[] cols = null;
  5. public read() throws ClassNotFoundException, IOException {
  6. cols = new String[]{"c1", "c2", "c3",};
  7. DefaultTableModel model = (DefaultTableModel) table.getModel();
  8. model.setColumnIdentifiers(cols);
  9. File f = new File("words.txt");
  10. FileInputStream fis = new FileInputStream(f);
  11. ObjectInputStream ois = new ObjectInputStream(fis);
  12. Object[] data = (Object[]) ois.readObject();
  13. model.addRow(data);
  14. pane = new JScrollPane(table);
  15. pane.setBounds(100, 150, 300, 300);
  16. setLayout(null);
  17. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  18. setVisible(true);
  19. setLocationRelativeTo(null);
  20. setSize(500, 500);
  21. }
  22. public static void main(String[] args) throws ClassNotFoundException, IOException {
  23. new read();
  24. }
  25. }

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

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

暂无答案!

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

相关问题