java - Java GUI 将文本文件数据导入 JTable
问题描述
我正在为我的作业编写一个程序,它应该将一些用户输入数据从 GUI(jtextfield) 获取到文本文件,然后将这些数据从文本文件检索到另一个 GUI(JTable)。
我有一些关于文件处理和 JAVA swing 的基本知识,但我现在遇到了一些问题。
首先,请让我告诉我现在做了什么(下面的代码)。
- 附加数据
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();
}
}
它现在正在工作,但它只从文件中检索一条数据,我希望它显示添加到文件中的所有数据。
我的问题是:
- 我的文字文件看起来不同:
我不确定它只是我还是它应该是什么?因为我希望它应该与我写的完全一致,所以即使 addrow(object) 方法不起作用,我也可以使用 getline 添加行。
- (重要)因为我将多个不同的数据写入单词文件(及其如上图所示),但它只显示一个。我认为这是因为我应该在 read.java 中的表中添加一个对象数组,而不仅仅是 addrow(object) 但我不知道如何,我的意思是我不知道如何让数组识别出有很多对象在单词文件中。另外,可以将数据作为对象写入文件并在 read.java 中检索它们,这是正确的方法吗?
谁能告诉我怎么做,谢谢你的帮助。请不要犹豫,问我是否没有正确说明。
解决方案
推荐阅读
- git - 如何将“Git Bash Here”添加到现有的 git 安装中
- python - 我在 python selenium 中找不到以下元素
- c# - 如何使用 C# async/await 作为独立的 CPS 转换
- javascript - 如何访问数组数据
- javascript - 我怎样才能在不匹配的情况下随机播放两个 js 数组
- unix - ls -l 和 sed 都是打印输出,但我只需要后者这样做
- javascript - 使用布尔值
- python - 使用 Selenium/Python 旋转代理
- google-sheets - 在谷歌表格中跨列拖动带有importrange的公式
- postgresql - 使用 psycopg2 的 Ansible 和 postgresql 错误