TestDefaultTableModel--table model in java&sql

本文介绍了一个使用Java Swing创建表格的示例程序,通过连接数据库并读取数据到JTable组件中。示例展示了如何定义表格模型DefaultTableModel,并填充数据库查询结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


//email:244910075@qq.com; 

//function:calling database in java table model

package javaSwing;


import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;


public class TestDefaultTableModel extends JFrame
{
Vector colsv=new Vector();
JTable table;
DefaultTableModel tablemodel;//Create the model of DefaultTable
public TestDefaultTableModel(){
this.setLayout(new FlowLayout());
/*
*将String对象“学号”、“姓名”、“生日”、“数学”加入向量中
*用以显示表头
*/
colsv.add("stu_num");
colsv.add("name");
colsv.add("birthday");
colsv.add("math");
colsv.add("english");
tablemodel=new DefaultTableModel(new Vector(),colsv);//Make an object of table model,with the initial vector'colsv'
String str="select * from stu_info";
TestDB db=new TestDB();
ResultSet rs=db.query(str);
/*
*Put the query resultset into the vector
*/
Vector value=new Vector();
try{
while(rs.next()){
Vector vc=new Vector();
vc.add(rs.getString(1));
vc.add(rs.getString(2));
vc.add(rs.getString(3));
vc.add(rs.getString(4));
vc.add(rs.getString(5));
value.add(vc);
}
tablemodel.setDataVector(value,colsv);//Write new raws into the table,and the value is vector value
}catch(SQLException e){
//TODO Auto-generated catch block
e.printStackTrace();
}
table=new JTable(tablemodel);
this.add(new JScrollPane(table));
this.setSize(500,200);
this.setVisible(true);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){//Set the listener:The program is over while the window is closed
System.exit(0);
}
});
}
public static void main(String[] args) 
{
new TestDefaultTableModel();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值