Java编程题:关于I/O流的

我是一名Java初学者,有这么一道题,希望高手能帮忙解决一些,谢谢!

用文本文件(不能用数据库)实现以下试验:
1.要用I/O流实现
2.可以修改货品的价格,数量,

假设有一家商店,需要一个存货目录来记录有哪些工具,每种工具有多少,每种工具的价格。编写一个应用程序对hardware.dat 文件进行操作。使工具信息存放在文件hardware.dat 中,并能够读入每条工具的信息,能列出所有工具,并能修改文件的任何信息。
使用以下数据

工具名称 数量 价格
锤子 128 10.00
锯子 16 14.25
电锯 8 79.50
螺丝刀 236 5.00
扳手 65 6.50

我尝试着用一个JTable实现一个表格,读取hardware.dat的数据填入表格的表头和表格中,可是不知道如何将数据按字符串读取后赋予定义表头和表格中,希望高手指导,不胜感谢!
当然,若有其他更简单的实现方法也可。
谢谢你的回答,你给的代码我已经能够实现,关键正是你说的表头和表格数据的动态初始化。我需要从hardware.dat文件中读取表头、表格数据赋予所创建的JTable,而不是自己在程序中给出,但是不知道如何采用何种格式读取和赋值?还希望你能够给我一个完整的实现代码,好吗?谢谢啦!

你应该参考一下JTable的实例

你这里的问题是动态初始化吗?

这个问题不是很大的 你可以用TablbModel初始化

TableModel负责对数据的控制 而JTable属于View

下面这个例子是从你给的数据生成一个界面的

package components;

/*
* SimpleTableDemo.java requires no other files.
*/

import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.File;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class SimpleTableDemo extends JPanel {
private final String RESOUCE_PATH = "resource\\";

public SimpleTableDemo() {
super(new GridLayout(1, 0));

Vector columnNamesVec = new Vector();
columnNamesVec.add("Utility Name");
columnNamesVec.add("Amount");
columnNamesVec.add("Price");

Vector rowsData = new Vector();
for (int i = 0; i < 10; i++) {
rowsData.add(new Vector());
for (int j = i; j < i + 3; j++) {
((Vector) rowsData.get(i)).add(String.valueOf(j));
}
}

String[] columnNames = { "Utility Name", "Amount", "Price" };

Object[][] data = {};

// final JTable table = new JTable(data, columnNames);
final JTable table = new JTable(rowsData, columnNamesVec);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
// table.setFillsViewportHeight(true);

//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);

//Add the scroll pane to this panel.
add(scrollPane);
}

/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.
SimpleTableDemo newContentPane = new SimpleTableDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);

//Display the window.
frame.pack();
frame.setVisible(true);
}

public void talbeInit(File file) {

}

public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

参考资料:http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

温馨提示:答案为网友推荐,仅供参考
大家正在搜