怎么把.txt文件内容导入jtable
怎么把.txt文件内容导入jtable
思路是什么?最好有个例子
------解决方案--------------------主要就是两步
1。通过io读txt文件,可以是一行一行的读
2。将读到的数据放到jtable的指定的cell里
基本上遍历一遍txt文件或遍历一遍jtable的cell就可以了
------解决方案--------------------这个应该可以构造一个vector的吧,每读一行的数据用vector来接收,再放在第一个vector中,应该可以的,不过如果数据量大,最好还是一行一行处理。
可以用modal.add来新增table中的行
------解决方案--------------------package laji;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import java.awt.Rectangle;
import javax.swing.JTable;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.table.DefaultTableModel;
import java.io.RandomAccessFile;
import java.util.Vector;
public class Frame1 extends JFrame {
public Frame1() {
try {
jbInit();
this.setBounds(100,100,400,400);
this.setVisible(true);
} catch (Exception exception) {
exception.printStackTrace();
}
}
private void jbInit() throws Exception {
getContentPane().setLayout(null);
jScrollPane1.setBounds(new Rectangle(11, 10, 408, 241));
jButton1.setBounds(new Rectangle(153, 274, 90, 37));
jButton1.setText("jButton1");
jButton1.addActionListener(new Frame1_jButton1_actionAdapter(this));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(jScrollPane1);
this.getContentPane().add(jButton1);
jScrollPane1.getViewport().add(jTable1);
}
public static void main(String[] args) {
Frame1 frame1 = new Frame1();
}
JScrollPane jScrollPane1 = new JScrollPane();
JTable jTable1 = new JTable();
JButton jButton1 = new JButton();
public void jButton1_actionPerformed(ActionEvent e) {
RandomAccessFile raf=null;
Vector data=new Vector();
String tmp="";
String[] temp;
try {
raf=new RandomAccessFile("D:\\demo\\laji\\data.txt","r");
while((tmp=raf.readLine())!=null){//读一行数据,然后通过","分割放到ROW里
temp=tmp.split(",");
Vector row=new Vector();
for(int i=0;i<temp.length;i++){
row.add(temp[i]);
}
data.add(row);
}
} catch (Exception ex) {
ex.printStackTrace();
}
// String[] title1=new String[]{"列1","列2","列3","列4"};
Vector title=new Vector();
title.add("列1");
title.add("列2");
title.add("列3");
title.add("列4");
// String[][] data=new String[][]{{"1","2","3","4"},{"1","2","3","4"},{"1","2","3","4"}};
DefaultTableModel dtm=new DefaultTableModel(data,title);
jTable1.setModel(dtm);
}
}
class Frame1_jButton1_actionAdapter implements ActionListener {
private Frame1 adaptee;
Frame1_jButton1_actionAdapter(Frame1 adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.jButton1_actionPerformed(e);
}
}